为什么link_libraries(stdc ++ fs)可以工作,但-lstdc ++ fs不能工作? [英] Why does link_libraries(stdc++fs) work but not -lstdc++fs?

查看:1289
本文介绍了为什么link_libraries(stdc ++ fs)可以工作,但-lstdc ++ fs不能工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用CMake / g ++ 8.1在Ubuntu上编译C ++ 17程序

I was trying to compile a C++17 program on Ubuntu using CMake/g++ 8.1 which contained

#include <filesystem>

当我使用此

set(CMAKE_CXX_FLAGS "-lstdc++fs")

我得到了一个奇怪的链接器错误

I got a weird linker error

undefined reference to `std::filesystem::__cxx11::recursive_directory_iterator::~recursive_directory_iterator()'

当我尝试使用 -lstdc ++ fs手动调用g ++时,也会出现此错误标志。

另一方面,这行符合我的预期

On the other hand, this line worked as I expected

link_libraries(stdc++fs)

我很好奇为什么这两行提供不同的结果。 link_libraries()函数使用某些我不知道的魔术吗?

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?

推荐答案

这将更改编译器标志,但不会更改链接标志:

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)

而不是 link_libraries (这是旧式CMake,不适合处理多个目标)。

instead of link_libraries (which is old style CMake and is not great at handling multiple targets).

target_link_libraries ,因为它只会将库添加到 target PRIVATE 还指示不传播共享库的链接(即从属库将不会链接到 stdc ++ fs ) 。

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

这篇关于为什么link_libraries(stdc ++ fs)可以工作,但-lstdc ++ fs不能工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆