Reputation: 667
I created some useful utility functions in C that I want to use in my programs. They are all located in the ../lib folder. I have a header file that contains the function prototypes which I include with `#include "../lib/library.h". However when compiling with gcc I also have to provide the names of the C files that contain the function definitions.
Right now there are only 3 C files in the ../lib folder but this may grow over time. Is there any way to automatically tell gcc to include all of these files (including my main.c file) when compiling my program?
Upvotes: 0
Views: 449
Reputation: 1977
Create a library. If you are on Linux, you have to choose if you want a static library or a shared library. Static libraries are created using archiver command on linux. Google for "ar".
ar cr libtest.a test1.o test2.o
Now you can link with this archive using the -ltest option (ltest is shorthand for libtest you created) with gcc or g++. If your code just has C code then use gcc. If it has both C and C++ then use g++.
As with header files, the linker looks for libraries in some standard places, including the /lib and /usr/lib directories that contain the standard system libraries. If you want the linker to search other directories as well, you should use the -L option, which is the parallel of the -I option for header files.You can use this line to instruct the linker to look for libraries in the /usr/local/lib/MyTest directory before looking in the usual places:
g++ -o reciprocal main.o reciprocal.o -L/usr/local/lib/MyTest -ltest
Although you don’t have to use the -I option to get the preprocessor to search the current directory (for finding you Header file), you do have to use the -L option to get the linker to search the current directory. In particular, you could use the following to instruct the linker to find the test library in the current directory:
gcc -o app app.o -L. -ltest
The shared library creation process is also similar. Once you get the hang of it then you can take care of compilation and linking via a makefile.
(Some part of this post was taken from: Advanced Linux Programming , link: http://www.cse.hcmut.edu.vn/~hungnq/courses/nap/alp.pdf)
Upvotes: 2