Why does link_libraries(stdc++fs) work but not -lstdc++fs? [duplicate]

给你一囗甜甜゛ 提交于 2020-04-16 06:07:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!