【问题标题】:How to add -lstdc++fs in Eclipse C++ for filesystem?如何在 Eclipse C++ 中为文件系统添加 -lstdc++fs?
【发布时间】:2018-12-06 10:12:30
【问题描述】:

这是一个在 c++ filesystem 上的演示 filesystem-testing.cpp 在命令行中工作:

环境:gcc/5.5.0

#include <iostream>
#include <string>
#include <experimental/filesystem>

int main()
{
    std::string path = std::experimental::filesystem::current_path();

    std::cout << "path = " << path << std::endl;
}

这里是编译和测试:

$ g++ -std=c++11 filesystem-testing.cpp -lstdc++fs
$ ./a.out
path = /home/userid/projects-c++/filesystem-testing

如何在Eclipse GCC C++ Compiler 和/或GCC C++ Linker 中添加-lstdc++fs

以下方式无效,有undefined reference'_ZNSt12experimental10filesystem2v112current_pathB5cxx11Ev'

1.案例A

2。案例B

【问题讨论】:

标签: c++ eclipse eclipse-cdt


【解决方案1】:

您提供的示例命令行通过单个命令从源文件创建可执行文件,但通常分两步完成:

g++ -c -std=c++11 filesystem-testing.cpp  # creates filesystem-testing.o
g++ filesystem-testing.o -lstdc++fs       # creates a.out

第一步调用编译器,第二步调用链接器(g++ 是两者的驱动程序)。

注意-lstdc++fs 标志属于链接器命令,而不是编译器命令。

Eclipse 的托管构建系统也在这两个步骤中执行编译。因此,您需要在链接器选项中指定-lstdc++fs(例如Tool Settings | GCC C++ Linker | Linker flags)。


更新:好的,我试过了,我发现将标志添加到Linker flags 是不够的。

要了解原因,让我们看一下控制台视图中的输出:

23:13:04 **** Incremental Build of configuration Debug for project test ****
Info: Internal Builder is used for build
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -o test.o ../test.cpp 
g++ -lstdc++fs -o test test.o 
test.o: In function `main':
/home/nr/dev/projects/c++/test/Debug/../test.cpp:7: undefined reference to `std::experimental::filesystem::v1::current_path[abi:cxx11]()'
collect2: error: ld returned 1 exit status

23:13:05 Build Failed. 1 errors, 0 warnings. (took 880ms)

请注意,它会向您显示它正在运行的命令。它正在运行的链接器命令是:

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

这与我在上面写的一个重要方面不同:-lstdc++fs 选项位于需要它的输入文件 (test.o) 之前,而不是之后。 Order matters 用于 GCC 链接器。

要解决这个问题,我们需要让 Eclipse 更改构建系统的参数顺序。您可以通过修改Tool Settings | GCC C++ Linker | Expert settings | Command line pattern 来做到这一点。这基本上是 Eclipse 如何构建链接器命令行的模式。它的默认值为:

${COMMAND} ${FLAGS} ${OUTPUT_FLAG} ${OUTPUT_PREFIX}${OUTPUT} ${INPUTS}

注意${FLAGS}-lstdc++fs 所在的位置)在${INPUTS}test.o 所在的位置)之前的位置。

让我们重新排序:

${COMMAND} ${OUTPUT_FLAG} ${OUTPUT_PREFIX}${OUTPUT} ${INPUTS} ${FLAGS}

然后再次尝试构建:

23:20:26 **** Incremental Build of configuration Debug for project test ****
Info: Internal Builder is used for build
g++ -o test test.o -lstdc++fs 

23:20:26 Build Finished. 0 errors, 0 warnings. (took 272ms)

现在一切都好!

更新 2:以下内容与快照中突出显示的内容一样。重要的是不要添加 -l

【讨论】:

  • @caot:“更新 2”中提到的解决方案是一种不同的方法:您将其添加到 Libraries 列表中,因此您不需要 -l 前缀,因为它会被添加自动用于图书馆。我建议把它放在需要-lLinker flags 中。
  • 将其放入 Eclipse 调用的链接器标志中不起作用:GCC C++ 链接器为g++ -lstdc++fs -o ...。唯一可行的方法是-lstdc++fs 位于最后,格式为g++ -o ... -o ... -lstdc++fs
  • @caot:您是否阅读了我的回答中关于在Command line pattern 中移动标志的“更新”部分?
猜你喜欢
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
相关资源
最近更新 更多