Reputation: 489
How can I use a static library in a C++ program that I have created?
For example, lets say I preform the following actions:
1. First I create file: foo.h
, and add the following code:
int foo(int a);
2. In turn I create foo.cpp
, and I add the following:
#include foo.h
int foo(int a)
{
return a+1;
}
3. Then I use GNU's C++ compiler GCC (except I use the G++ version) which looks something like the following:
3a.
g++ foo.cpp
3b.ar rc libfoo.a foo.o
4. I create my program's main file, main.cpp
"main.cpp"
#include "foo.h"
int main()
{
int i = foo(2);
return i;
}
main.cpp
?What I am attempting to do is the following:
g++ -L. -lfoo prog.cpp
but get an error because the function foo would not be found
Upvotes: 17
Views: 31961
Reputation:
You want:
g++ -L. prog.cpp -lfoo
Unfortunately, the ld linker is sensitive to the order of libraries. When trying to satisfy undefined symbols in prog.cpp, it will only look at libraries that appear AFTER prog.cpp on the command line.
You can also just specify the library (with a path if necessary) on the command line, and forget about the -L flag:
g++ prog.cpp libfoo.a
Upvotes: 21