我在ld中遇到了一些“未定义的引用”错误,并且不知道是什么导致了它们。
我的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
等等。 (实际上,还有更多的库,但这是一般的想法。)
MyUI
,MyBusinessLogic
和MyUtil
都是我已经构建的动态库。为了简化makefile的编写,GUI和命令行程序使用相同的库列表,即使命令行程序不需要libMyUI.so
。
当我尝试链接它时,有一个且只有一个命令行程序会对Boost.Regex符号的未定义引用提供大量错误,即使我将-lboost_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符号?为什么删除看似无关的库会修复它?为什么其他程序没有任何问题链接?
答案 0 :(得分:2)
至少我已经找到了答案的大部分内容。由于我的makefile规则存在一些问题,libMyUI.so
与boost_regex
相关联,但libMyBusinessLogic.so
没有。我猜测,因此,在链接器知道MyUI
需要的所有符号之前,链接boost_regex
导致MyBusinessLogic
过早被拉入。
只要我保持一致 - 要么所有My*.so
都与boost_regex
相关联,要么都没有 - 这一切都有效。我不确定哪种解决方案最受欢迎,但至少我有一个解决办法。