2

我在 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 符号?为什么删除看似无关的库会修复它?为什么其他程序链接没有任何问题?

4

1 回答 1

2

我至少已经找到了大部分答案。由于我的makefile规则有些草率,libMyUI.so被链接到boost_regex,但libMyBusinessLogic.so没有。我猜想,因此,在链接器知道它需要的所有符号之前,链接会MyUI过早地被拉入。boost_regexMyBusinessLogic

只要我是一致的——要么全部My*.so链接到boost_regex,要么没有一个链接——一切正常。我不确定这些解决方案中的哪一个是最受青睐的,但至少我有一个解决方案。

于 2013-10-10T22:15:58.377 回答