How to add a static library (.a) to a C ++ program?

I want to know how I can use the static library in C ++ that I created, first lib:

// header: foo.h int foo(int a); 

.

 // code: foo.cpp #include foo.h int foo(int a) { return a+1; } 

then I will compile the library first:

  • g ++ foo.cpp
  • ar rc libfoo.a foo.o

Now I want to use this library in some kind of file, for example:

 // prog.cpp #include "foo.h" int main() { int i = foo(2); return i; } 

how should i compile them now? I did:

 g++ -L. -lfoo prog.cpp 

but get an error because the foo function will not be found

+4
source share
1 answer

Do you want to:

 g++ -L. prog.cpp -lfoo 

Unfortunately, the ld linker is sensitive to the order of the libraries. When trying to satisfy undefined characters in prog.cpp, it will only look at the libraries that appear AFTER prog.cpp on the command line.

You can also simply specify the library (with the path if necessary) on the command line and forget about the -L flag:

 g++ prog.cpp libfoo.a 
+9
source

All Articles