测试给我提了一个BUG,咱们的程序在链接HTTPS服务端后,莫名crash。
在还原测试环境后,经过gdb调试,发现crash在libcurl的curl_easy_platform这个函数里面,因而开启了漫长的debug之旅,最终发现是函数符号冲突所致。curl
静态库libA.a 动态库libB.so 可执行二进制test.bin
静态库A主要导出一个函数接口TestFunc
主要代码:函数
extern "C" void TestFunc(std::string const& strData) { std::cout<<"This is libtestA"<<std::endl; std::cout<<strData<<std::endl; }
动态库B导出两个函数接口,一个TestFunc,另外一个函数调用静态库A的TestFunc 主要代码:测试
extern "C" __attribute__((visibility("default"))) void TestFunc(std::string const& strData) void TestFunc(std::string const& strData) { std::cout<<"This is libtestB"<<std::endl; std::cout<<strData<<std::endl; } extern "C" __attribute__((visibility("default"))) void TestFunc_Ex() { //写一个测试类,经过类里面Test函数调用静态库A的TestFunc函数 TestClass _t; _t.Test(); }
test.bin调用动态库B里面的两个函数接口
主要代码:编码
int main() { TestFunc("hoho"); TestFunc_Ex(); return 0; }
This is libtestB hoho This is libtestB TestClass::Test
若是将静态库A导出的函数的参数修改成空,那么从新编译后,再运行test.bin,就复现了crash。url
This is libtestB hoho This is libtestB Segmentation fault (core dumped)
理想中的结果应该是:.net
This is libtestB hoho This is libtestA TestClass::Test
出现这个问题的缘由是:
在Linux下,全部同名函数,都会被第一个加载的函数符号所代替,因此test.bin调用的时候,所有都走了动态库B的TestFunc函数。debug
遇到这种函数符号冲突的问题,编译器一般不会给你任何提示。出现crash,只能经过gdb和经验来一步一步排查。
解决方法能够经过编译传参数来指定导出函数来解决,但我不建议这种方法。在大型项目中添加多余的编译参数及文件是一种很挫的作法。我仍是建议在编码中注意规范,多检查、多用命名空间来约束、避免这类问题。调试
示例代码Demo下载地址code