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

大憨熊 提交于 2020-01-30 04:12:17

问题


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 because the function foo would not be found


回答1:


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


来源:https://stackoverflow.com/questions/5870026/howto-add-a-static-library-a-into-a-c-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!