如何在C ++程序中添加静态库(.a)? [英] howto add a static library (.a) into a C++ program?

查看:520
本文介绍了如何在C ++程序中添加静态库(.a)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在我创建的C ++中使用静态库,首先是lib:

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;
}

然后我首先编译该库:

  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

但是由于找不到函数foo而收到错误消息

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

推荐答案

您要:

g++ -L.  prog.cpp -lfoo

不幸的是,ld链接器对库的顺序很敏感.当尝试满足prog.cpp中的未定义符号时,它将仅查看在prog.cpp之后出现在命令行上的库.

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.

您还可以只在命令行上指定库(如果需要,则带有路径),而无需使用-L标志:

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

这篇关于如何在C ++程序中添加静态库(.a)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆