cmake,boost :: filesystem links error(undefined directory_iterator.operator!=)

时间:2011-02-27 01:48:19

标签: c++ boost linker cmake

我在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中标题的内容,我可以看到在那里定义了运算符。任何想法为什么会发生这种情况?

我非常感谢你的帮助。

2 个答案:

答案 0 :(得分:2)

添加缺少的包含文件后:

#include <string>
#include <iostream>

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

#define fs boost::filesystem

然后我尝试了你提到的第一个CMakeLists.txt方法,它起作用了......我也有与你相同的系统。

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

答案 1 :(得分:0)

我有同样的问题,除了我的编译器(VS 2010)抱怨没有运算符!=采用类型&#39; boost :: filesystem3 :: directory_iterator&#39;的左手操作数。事实证明我已经声明了我的结束迭代器:

boost::filesystem::directory_iterator endDir();

当我删除括号时,编译和链接的一切都很好。我想编译器将原始行解释为名为endDir的函数,它返回directory_iterator,但仍然没有解释为什么它抱怨左操作数,而不是右手操作数。

Scott Meyers已将此问题描述为C++'s "most vexing parse."