gpt4 book ai didi

c++ - cmake, boost::filesystem 链接错误 (undefined directory_iterator.operator!=)

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:59:07 33 4
gpt4 key购买 nike

我在 Ubuntu 10.10 中使用 CMake (2.8.3)、Boost::filesystem(1.42.0)。代码编译正常,但在链接时我不断收到以下错误:

CMakeFiles/sample.dir/sample.cpp.o: In function `main':
sample.cpp:(.text+0x1af8d): undefined reference to `int operator!=<boost::filesystem::basic_directory_iterator<boost::filesystem::basic_path<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::filesystem::path_traits> > >(boost::filesystem::basic_directory_iterator<boost::filesystem::basic_path<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::filesystem::path_traits> > const&, boost::filesystem::basic_directory_iterator<boost::filesystem::basic_path<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::filesystem::path_traits> > const&)'
collect2: ld returned 1 exit status

有问题的代码如下:

#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>

int main()
{
string folder;
string extension;
fs::directory_iterator end;

folder = ".";
extension = ".zip";

for (fs::directory_iterator i(folder); i != end; ++i)
{ if (fs::is_regular_file(i->status()))
{
if (boost::algorithm::ends_with(i->leaf(), extension))
{
cout << i->leaf() << " has extension .zip" << endl;
}
}
}
}

在我的 CMakeLists.txt 文件中,我有:

find_package(Boost 1.4.0 COMPONENTS filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})

target_link_libraries(executable
${Boost_LIBRARIES})

但我也尝试过:

set(Boost_USE_STATIC_LIBS        ON)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost 1.4.0 COMPONENTS filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})

target_link_libraries(executable
${Boost_FILESYSTEM_LIBRARY})

以及以上的许多其他组合。

链接器提示 directory_iterator 类型的 != 运算符。如果我查看 /usr/include/boost/filesystem/path.cpp 中 header 的内容,我可以看到运算符是在那里定义的。知道为什么会这样吗?

非常感谢您的帮助。

最佳答案

添加缺失的包含文件后:

#include <string>
#include <iostream>

和命名空间 (std),并为代码的这个“fs”快捷方式定义一个宏:

#define fs boost::filesystem

然后我尝试了你提到的第一个 CMakeLists.txt 方法,它奏效了......我也有和你一样的系统。

我建议在 CMake 中使用 MESSAGE 检查这些 $Boost_* 变量并用它调试编译系统......

关于c++ - cmake, boost::filesystem 链接错误 (undefined directory_iterator.operator!=),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5130902/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com