链接到静态库以生成静态可执行文件



我正在尝试构建一个C程序的静态可执行文件,该程序需要Postgresql-libecpg-dev包中的以下库:libecpg、libpq和libpgtypes。静态库libecpg.a、libpq.a和libpgtypes.a都与其动态版本/usr/lib位于同一位置。无论如何,我已经尝试添加-L选项作为他们的路径,但我得到了相同的结果。

我的可执行文件需要是静态的,这样二进制文件就可以移植,这样用户就不必将库安装到他们的系统上才能使用它。当我对动态库使用以下命令时,程序构建得很好:(我正在使用的一些Postgresql函数必须包含-I目录)

 gcc main.o -lecpg -lpq -lpgtypes -I/usr/include/postgresql -o program_name

当我尝试链接到静态库时,我使用以下命令:

gcc -static main.o -lecpg -lpq -lpgtypes -I/usr/include/postgresql -o program_name 

然而,编译器会给我一长串"未定义引用"错误作为输出。有这么多,但这里有一个小样本:

/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libecpg.a(descriptor.o):
In function `get_descriptors':
(.text+0xc3): undefined reference to `pthread_once'
 /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libecpg.a(descriptor.o): In function `ECPGdeallocate_desc':
(.text+0x2c6): undefined reference to `pthread_setspecific'
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libecpg.a(descriptor.o): In function `ECPGallocate_desc':
(.text+0x376): undefined reference to `pthread_setspecific'
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libecpg.a(descriptor.o): In function `get_descriptors':
(.text+0xd2): undefined reference to `pthread_getspecific'

当我更改订单如下:

gcc -I/usr/include/postgresql -static -lecpg -lpq -lpgtypes -o program_name main.o

相反,编译器输出看起来如下(再一次,只是一个小采样):

main.c:(.text+0x5c6): undefined reference to `ECPGconnect'
main.c:(.text+0x83e): undefined reference to `ECPGdo'
main.c:(.text+0x843): undefined reference to `ECPGget_sqlca'
main.c:(.text+0x85c): undefined reference to `ECPGdisconnect'
main.c:(.text+0x87c): undefined reference to `ECPGget_sqlca'

我试过在所有地方使用-I选项(以及所有其他选项),但似乎都不起作用。

我认为您再也无法在现代Linux发行版中创建一个完全静态的非平凡的可执行文件了。但是您可以静态地包含一些特定的库。

这样试试:

 gcc main.o /usr/include/postgresql/libecpg.a /usr/include/postgresql/libecpg.a /usr/include/postgresql/libpq.a /usr/include/postgresql/libpgtypes.a -o program_name

最新更新