Question

I have written some code in Lib_file.h and Lib_file.cpp. I wish to convert this code to a static library. I am able to compile the code (using the command g++ -I <necessary include files> -o Lib_file.o Lib_file.cpp)to get Lib_file.o. I am also able to add it to an archive using the ar rvs Lib_file.a Lib_file.o command. Now when I try to use this library in some other code using the -L option, I get undefined reference errors. This errors point to the code in my Lib_file.o . So my question is how do I get the code in my Lib_file.cpp to link to the libraries that it uses.

I have tried the following options so far

I. After creating the Lib_file.o, I tried the following command g++ -L<include path> -l<.a files> Lib_file.o . On executing this command, I get the following error

/usr/lib/../lib64/crt1.o: In function `_start':
init.c:(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status

II. I tried to include all the necessary .a files in a new archive along with my Lib_file.o using the ar command. Still I get the undefined reference error when I try to use the Lib_file.a library with my application

Please help me out here

Was it helpful?

Solution

First of all, all libraries are normally named something like libxyz.a where xyz is the name of the library.

Secondly, you try to create a program using only the object file you used for the library, and also linking it with itself. This will of course not work, since the library have no main function which is needed for normal programs. You have to create another program, and link that one with the library.

Like

gcc myotherprogram.c -o myotherprogram -L/some/path -lxyz

As you can see in my command line above, I placed the library last on the command line. It's needed because the linker look for dependencies in kind of reversed order.

Edit: Linking your static library with other libraries: You don't. A static library is completely standalone, and if it needs other libraries itself to work then they have to be present on the command line when compiling the actual program.

For example, lets say that library xyz depends on the standard math library (i.e. the m library). You can't "link" with it when creating the xyz library as you don't actually link static libraries, you just put a collection of object files together in an archive (ar and the .a extension is for archive). When you build the actual application that needs the xyz library you also needs to link with whatever libraries that xyz needs:

gcc myotherprogram.c -o myotherprogram -L/some/path -lxyz -lm
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top