问题
I was trying to compile a C++17 program on Ubuntu using CMake/g++ 8.1 which contained
#include <filesystem>
When I used this
set(CMAKE_CXX_FLAGS "-lstdc++fs")
I got a weird linker error
undefined reference to `std::filesystem::__cxx11::recursive_directory_iterator::~recursive_directory_iterator()'
This error also appeared when I tried calling g++ manually with the -lstdc++fs
flag.
On the other hand, this line worked as I expected
link_libraries(stdc++fs)
I'm curious as to why these two lines provide different results. Does the link_libraries()
function use some magic I'm not aware of?
回答1:
This changes the compiler flags, but not the link flags:
set(CMAKE_CXX_FLAGS "-lstdc++fs")
This means that when you compile the file, you add the library, which has no effect, and then when you link to create your executable, you don't get this flag.
So you should actually change the linker with:
target_link_libraries(target PRIVATE stdc++fs)
instead of link_libraries
(which is old style CMake and is not great at handling multiple targets).
target_link_libraries
is advised as it only adds the library to target
. PRIVATE
also indicates not to propagate the link for shared libraries (i.e. dependent libraries will not link against stdc++fs
).
You can check the difference in behavior between the two by doing:
VERBOSE=1 make
来源:https://stackoverflow.com/questions/53801547/why-does-link-librariesstdcfs-work-but-not-lstdcfs