I’m attempting to use a C library for an opencourseware course from Harvard. The instructor’s instructions for setting up the external lib can be found here.
I am following the instructions specific to ubuntu as I am trying to use this lib on my ubuntu box. I followed the instructions on the page to set it up, but when I run a simple helloWorld.c program using a cs50 library function, gcc doesn’t want to play along.
Example:
helloWorld.c
#include <stdio.h>
#include <cs50.h>
int
main(void){
printf("What do you want to say to the world?\n");
string message = GetString();
printf("%s!\n\n", message);
}
$ gcc helloWorld.c
/tmp/ccYilBgA.o: In function `main':
helloWorld.c:(.text+0x16): undefined reference to `GetString'
collect2: ld returned 1 exit status
I followed the instructions to the letter as stated in the instructions, but they didn’t work for me. I’m runing ubuntu 12.04. Please let me know if I can clarify further my problem.
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 invokegcc. 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
-Lfollowed by a library directory, then-lglued to the library name. So you might needgcc -Wall -g -lcs50(replacecs50by the appropriate name) and you might need some-Lsome-dirNotice that the order of program arguments to
gccis significant. As a general rule, ifadepends uponbyou should putabeforeb; more specifically I suggestgccprogram name; add the C standard level eg-std=c99if wanted-Wall -g(you may even want to add-Wextrato get even more warnings).-DONE=1and-Imy-include-dir/hello.cbar.o-Lmy-lib-dir/if relevant-laaand-lbb(when thelibaa.sodepends uponlibbb.so, in that order)-o your-program-nameto give the name of the produced binary. Don’t use the default namea.outDirectory giving options
-I(for preprocessor includes) and-Lfor 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 ofremakeon 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
guileon Linux while reading it, see http://norvig.com/21-days.html for more). Be also aware of tools like valgrindHave fun.