开发者

howto add a static library (.a) into a C++ program?

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

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

.

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

then I compile the library first:

  1. g++ foo.cpp
  2. ar rc libfoo.a foo.o

now I want to use these library in some file like:

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

how must I compile these now? I made:

g++ -L. -lfoo prog.cpp

but get an error becaus开发者_JS百科e the function foo would not be found


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜