c++ - 添加 -l 标志*在*其余标志之后

标签 c++ cmake g++

我正在尝试使用实验性/文件系统

我首先尝试通过 CMake 在我的项目中直接使用它,方法是添加:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lstdc++fs")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lstdc++fs")

这没有用,抛出一个长而难以阅读的错误:

CMakeFiles/miner.dir/Main.cpp.o: In function `main':
Main.cpp:(.text+0x33): undefined reference to `std::experimental::filesystem::v1::create_directories(std::experimental::filesystem::v1::__cxx11::path const&)'
CMakeFiles/miner.dir/Main.cpp.o: In function `std::experimental::filesystem::v1::__cxx11::path::path<char [6], std::experimental::filesystem::v1::__cxx11::path>(char const (&) [6])':
Main.cpp:(.text._ZNSt12experimental10filesystem2v17__cxx114pathC2IA6_cS3_EERKT_[_ZNSt12experimental10filesystem2v17__cxx114pathC5IA6_cS3_EERKT_]+0x73): undefined reference to `std::experimental::filesystem::v1::__cxx11::path::_M_split_cmpts()'
collect2: error: ld returned 1 exit status
CMakeFiles/miner.dir/build.make:123: recipe for target 'miner' failed
make[2]: *** [miner] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/miner.dir/all' failed
make[1]: *** [CMakeFiles/miner.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

无论如何,我不确定为什么会发生这种情况,直到我意识到出于某种原因——与文件系统有关的静态库——我需要-lstdc++11就在命令的末尾。

我用一个小文件测试了这个,只包含 <experimental/filesystem>并制作一些目录(代码并不重要)。

我用这些命令构建了它:

g++ -c test.cpp -lstdc++fs
g++ -o test test.o -lstdc++fs

这成功了。因此,我确信我认为 -lstdc++fs 是正确的。必须执行其余命令。

然后我使用了 make VERBOSE=1在我的大型 CMake 项目中,注意到它正在做与我想要的相反:它把 -lstdc++fs在命令的开头!

我确信 CMake 比我更了解它在做什么,这让我相信我做错了什么。 有什么办法可以用experimental/filesystem不在命令末尾放置标志?如果没有更好的方法,那么我希望 CMake 有办法做到这一点。

最佳答案

如果你想链接到一个库,告诉 CMake 并且不要乱用标志,就 CMake 而言,这些标志是一个黑盒子。只需这样做:

target_link_libraries(YourExeTarget stdc++fs)

关于c++ - 添加 -l 标志*在*其余标志之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46983630/

相关文章:

C++ 运算符重载参数与普通参数

c++ - 禁用特定 MSVC 版本的优化

c++ - 内联汇编 : operand type mismatch for 'out'

c++ - 二进制搜索数组溢出 C++

c++ - 如何在 C++ 中使用 while 循环读取文件?

c++ - 为什么这个函数不能用明显不同的签名之一重载?

c++ - 在 CMake 项目中包含 libsimdpp

c++ - CMake - 每次构建项目时如何停止构建每个依赖项

gcc - CLion + MinGW 测试 CMake 运行完成但出现错误

c++ - 为什么需要虚拟 thunk?