c++静态库的链接问题

Linking issue with C++ static libraries

本文关键字:链接 问题 静态 c++      更新时间:2023-10-16

我有2个静态库,我正在构建链接这两个库的1个可执行文件。这段代码编译/运行良好,直到我将Crc函数从library2移动到library1。在library1中,我定义了一个函数

uint16_t Crc16(const std::vector<uint8_t> &data);

在library2中我有一个函数

uint16_t MyClass::CalcChecksum()
{
    std::vector<uint8_t> payload(rawData.begin()+1, rawData.end()-FOOTER_SIZE);
    return Crc16(payload);
}

当我链接可执行文件时,我得到一个"对' Crc16'的未定义引用"。我的链接行是

g++ -rdynamic -Wl,-rpath,/home/chris/Qt5.3.0/5.3/gcc_64 -Wl,-rpath,/home/chris/Qt5.3.0/5.3/gcc_64/lib -o MyExecutable main.o server.o client.o service.o userserver.o pluginloader.o plugin.o moc_server.o moc_client.o moc_userserver.o moc_pluginloader.o moc_plugin.o   -L/home/chris/Dev/ProductName/build-ProductName-Desktop_Qt_5_3_0_GCC_64bit-Debug/MyExecutable/../StaticLibrary1/ -lStaticLibrary1 -L/home/chris/Dev/ProductName/build-ProductName-Desktop_Qt_5_3_0_GCC_64bit-Debug/MyExecutable/../StaticLibrary2/ -lStaticLibrary2 -ldl -L/home/chris/Qt5.3.0/5.3/gcc_64/lib -lQt5Network -lQt5Core -lpthread

当我检查libray1的导出时,我得到这个:

nm lib1.a | grep -i crc
000000000000041d T Crc16

和lib2我得到这个:

nm lib2.a | grep -i crc
                 U Crc16
我得到的实际错误是
/home/chris/Dev/ProductName/build-ProductName-Desktop_Qt_5_3_0_GCC_64bit-Debug/MyExecutable/../StaticLibrary2//libStaticLibrary2.a(message.o): In function `Device::Message::CalcChecksum()':
/home/chris/Dev/ProductName/ProductName/StaticLibrary2/message.cpp:392: undefined reference to `Crc16'

library1定义了函数,而library2将函数标记为未定义,这一事实是有意义的。没有意义的是,当链接一个可执行文件时,它抱怨函数是未定义的。

谢谢,克里斯。

由于library2依赖于library1,因此它需要首先列在链接行上。