我正在尝试编译一个简单的测试项目,以确保我的所有工具(如 CMake、Boost、Clang)都能正常工作。
我尝试编译的源代码是 LibLinkTest.cpp:
#include <boost/filesystem.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <assert.h>
using namespace boost::filesystem;
int main(int argc, char* argv[])
{
std::string str{"test passed"};
std::cout << str << std::endl;
boost::filesystem::path p{argv[1]};
try {
std::cout << p.string() << std::endl;
if (exists(p)) {
if (is_regular_file(p)) {
std::ifstream file{p.c_str()};
std::string line;
if (file.good() && file.is_open()) {
while (file >> line) {
std::cout << line << std::endl;
}
}
file.close();
} else if (is_directory(p)) {
std::cout << p.string() << " is a directory " << std::endl; // path stream inserter
} else
std::cout << p.string() << " exists, but is neither a regular file nor a directory" << std::endl;
}
else {
std::cout << p.string() << " does not exist" << std::endl;
}
}
catch (const filesystem_error& ex) {
std::cout << ex.what() << std::endl;
}
}
运行:
c++ -std=c++11 -I /usr/boost_1_54_0/boost/ LibLinkTest.cpp -o LibTest -L /usr/boost_1_54_0/lib/ -lboost_filesystem -lboost_system
编译得很好并且代码可以运行(有段错误,但我会单独解决)。
但是,我想在我的其他项目中使用 CMake。尝试使用以下 CMakeLists.txt 编译 LibLinkTest.cpp 会导致链接错误。
CMAKE_MINIMUM_REQUIRED (VERSION 2.6)
PROJECT(BoostTest CXX)
SET(CMAKE_CXX_FLAGS "-std=c++11 -stdlib=libc++")
FIND_PACKAGE(Boost 1.54.0 COMPONENTS filesystem system REQUIRED)
INCLUDE_DIRECTORIES(
${Boost_INCLUDE_DIR}
/usr/include/
/usr/include/c++/4.2.1/
)
ADD_EXECUTABLE(
LibTest
LibLinkTest.cpp
)
TARGET_LINK_LIBRARIES(LibTest boost_filesystem boost_system)
运行 cmake ../
的输出是:
-- The CXX compiler identification is Clang 5.0.0
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Boost version: 1.54.0
-- Found the following Boost libraries:
-- filesystem
-- system
-- Configuring done
-- Generating done
最后运行 make
给出错误:
Scanning dependencies of target LibTest
[100%] Building CXX object CMakeFiles/LibTest.dir/LibLinkTest.cpp.o
Linking CXX executable LibTest
Undefined symbols for architecture x86_64:
"std::string::c_str() const", referenced from:
boost::system::system_error::what() const in LibLinkTest.cpp.o
boost::filesystem::path::c_str() const in LibLinkTest.cpp.o
"std::string::empty() const", referenced from:
boost::system::system_error::what() const in LibLinkTest.cpp.o
"std::basic_ios<char, std::char_traits<char> >::good() const", referenced from:
_main in LibLinkTest.cpp.o
似乎 CMake 中的设置不正确,可能是指向标准 C++ 库的设置。有谁知道如何正确配置 CMake?
最佳答案
我已经通过更改行解决了这个问题:
SET(CMAKE_CXX_FLAGS "-std=c++11 -stdlib=libc++")
到
SET(CMAKE_CXX_FLAGS "-std=c++11 -stdlib=libstdc++")
我好像刚刚在 CMakeLists.txt 中打错了字。
旁注,有人知道我为什么需要设置这个标志吗?它是 C++11 的东西吗?它似乎也解决了我从命令行编译时遇到的段错误问题。
关于C++ 从命令行用 clang 编译,但不使用 CMake,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19757328/