First, as a beginner, you should always ask GCC to compile with all warnings and debugging information enabled, i.e. gcc -Wall -g
. But at some time read How to invoke gcc
. Use a good source code editor (such as GNU emacs or vim or gedit, etc...) to edit your C source code, but be able to compile your program on the command line (so don't always use a sophisticated IDE hiding important compilation details from you).
Then you are probably missing some Harvard specific library, some options like -L
followed by a library directory, then -l
glued to the library name. So you might need gcc -Wall -g -lcs50
(replace cs50
by the appropriate name) and you might need some -L
some-dir
Notice that the order of program arguments to gcc
is significant. As a general rule, if a
depends upon b
you should put a
before b
; more specifically I suggest
- Start with the
gcc
program name; add the C standard level eg -std=c99
if wanted
- Put compiler warning, debugging (or optimizing) options, eg
-Wall -g
(you may even want to add -Wextra
to get even more warnings).
- Put the preprocessor's defines and include directory e.g.
-DONE=1
and -Imy-include-dir/
- Put your C source file
hello.c
- Put any object files with which you are linking i.e.
bar.o
- Put the library directories
-Lmy-lib-dir/
if relevant
- Pur the library names
-laa
and -lbb
(when the libaa.so
depends upon libbb.so
, in that order)
- End with
-o your-program-name
to give the name of the produced binary. Don't use the default name a.out
Directory giving options -I
(for preprocessor includes) and -L
for libraries can be given several times, order is significant (search order).
Very quickly you'll want to use build automation tools like GNU make
(perhaps with the help of remake
on Linux)
Learn also to use the debugger gdb
.
Get the habit to always ask for warnings from the compiler, and always improve your program till you get no warnings: the compiler is your friend, it is helping you!
Read also How to debug small programs and the famous SICP (which teaches very important concepts; you might want to use guile
on Linux while reading it, see http://norvig.com/21-days.html for more). Be also aware of tools like valgrind
Have fun.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…