我在ld中遇到一些“ undefined reference ”错误,并且对导致它们的原因不知所措。

我的makefile使用如下命令构建几个可执行文件:

g++ -ogui_program1 -Lpath/to/MyLibs gui_program1.o -lMyUI -lMyBusinessLogic \
    -lMyUtil -lboost_regex
g++ -ogui_program2 -Lpath/to/MyLibs gui_program2.o -lMyUI -lMyBusinessLogic \
    -lMyUtil -lboost_regex
g++ -ocli_program1 -Lpath/to/MyLibs cli_program1.o -lMyUI -lMyBusinessLogic \
    -lMyUtil -lboost_regex
g++ -ocli_program2 -Lpath/to/MyLibs cli_program2.o -lMyUI -lMyBusinessLogic \
    -lMyUtil -lboost_regex

等等。 (实际上,比这更多的库,但这是一般的想法。)
MyUIMyBusinessLogicMyUtil都是我已经构建的动态库。为了简化makefile的编写,即使命令行程序不需要libMyUI.so,GUI和命令行程序也使用相同的库列表。

当我尝试链接Boost.Regex符号时,即使是将-lboost_regex与每个二进制文件链接在一起,命令行程序中也只有一个,它给出了很多错误,涉及到未定义的对Boost.Regex符号的引用:
libMyBusinessLogic.so: undefined reference to `boost::re_detail::perl_matcher >, boost::regex_traits > >::construct_init(boost::basic_regex > > const&, boost::regex_constants::_match_flags)'
libMyBusinessLogic.so: undefined reference to `boost::cpp_regex_traits::toi(char const*&, char const*, int) const'
libMyBusinessLogic.so: undefined reference to `boost::re_detail::perl_matcher, std::allocator > >, std::allocator, std::allocator > > > >, boost::regex_traits > >::match()'
libMyBusinessLogic.so: undefined reference to `boost::re_detail::perl_matcher, std::allocator > >, std::allocator, std::allocator > > > >, boost::regex_traits > >::construct_init(boost::basic_regex > > const&, boost::regex_constants::_match_flags)'
libMyBusinessLogic.so: undefined reference to `boost::re_detail::perl_matcher, std::allocator > >, std::allocator, std::allocator > > > >, boost::regex_traits > >::find()'
libMyBusinessLogic.so: undefined reference to `boost::basic_regex > >::do_assign(char const*, char const*, unsigned int)'
libMyBusinessLogic.so: undefined reference to `boost::re_detail::perl_matcher >, boost::regex_traits > >::match()'

链接所有其他程序都可以。如果我从一个命令行程序中删除了-lMyUI,那么即使MyUI不在错误列表中的任何地方都可以正常工作。

当我在命令末尾添加-lboost_regex时,为什么ld没有找到Boost.Regex符号?为什么删除看似无关的库可以解决此问题?为什么其他程序链接没有任何问题?

最佳答案

我至少已经找到了大部分答案。由于我的makefile规则有些草率,libMyUI.soboost_regex链接了,但libMyBusinessLogic.so却没有。我猜想,结果是,在链接器知道MyUI将需要的所有符号之前,链接boost_regex会导致MyBusinessLogic提前被拉入。

只要我保持一致-要么所有My*.so都链接到boost_regex,要么它们都不起作用-一切正常。我不确定这些解决方案中的哪一个是最优选的,但至少我有解决方法。

关于c++ - 来自不需要的库的未定义引用错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19306579/

10-11 23:07
查看更多