我正在尝试编译一个简单的测试项目,以确保我的所有工具(例如 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 中的设置不正确,可能指向 std c++ lib。有谁知道我如何正确配置 CMake?