【发布时间】:2012-01-13 23:16:35
【问题描述】:
我正在尝试将静态库的某些部分链接到在 Linux 下使用 g++ 用 C++ 编写的程序中。
my_lib.h
#ifdef USE_EXTERN_LIB
# include <extern_lib.h>
void do_something (struct extern_lib);
#endif
void do_other (int);
my_lib.c
#include "my_lib.h"
#ifdef USE_EXTERN_LIB
void do_something (struct extern_lib l)
{
// do something
}
#endif
void do_other (int a)
{
// do something
}
我正在使用 -DUSE_EXTERN_LIB 预处理器标志静态创建 libmy_lib.a 以将所有内容都包含在其中。
但我想做的是创建两个程序:一个将这个库与 *extern_lib* 一起使用,另一个在没有 *extern_lib* 的情况下使用它,即:
g++ -L/path/to/lib -lmy_lib -o prog_wihtout_lib prog_without_lib.cc
g++ -DUSE_EXTERN_LIB -L/path/to/lib -lmy_lib -o prog_with_lib prog_with_lib.cc
第二个程序编译但不是第一个,它说 extern_lib 未声明。
使用动态库没有问题,因为符号是在运行时加载的,但我想要一个静态库。 有没有办法只链接静态库的所需模块?
编辑
prog_without_lib.cc
#include "my_lib.h"
int main ()
{
do_other (42);
return 0;
}
prog_with_lib.cc
#include "my_lib.h"
int main ()
{
do_other (42);
struct extern_lib l;
do_something (l);
return 0;
}
谢谢。
【问题讨论】:
-
你能告诉我们“第二次”编译的确切错误吗?我将假设定义了
USE_EXTERN_LIB的第二种方法。 -
你是 my_lib.c 中的
#include "my_lib.h"吗? -
对不起,这是第一个没有编译的程序
-
你能贴出 prog_without_lib.cc 的源码吗?
-
它会自动执行此操作。如果静态库中的函数未在可执行文件中使用,则不会从库中复制到可执行文件中。