如何使用 Visual Studio 代码编译多 cpp 文件?

2022-01-23 00:00:00 visual-studio-code g++ c++

我已经按照一些说明构建了Visual Studio代码C/C++编译和调试环境.但是g++编译器只能编译选定的cpp文件,因此与cpp文件相关的包含的.h文件无法编译.然后终端显示架构 x86_64 的未定义符号"错误.代码如下:

I have followed some instructions to construct Visual studio code C/C++ compile and debug environment.But g++ compiler can only compile the selected cpp file, so the included .h file associated the cpp file can not compiled. then the terminal shows 'Undefined symbols for architecture x86_64' error. the code as below:

    int func();

a.cpp 文件

    include <iostream>
    include "a.h"
    using namespace std;
    int func(){
        return 111;
    }

main.cpp 文件

    include "a.h"
    using namespace std;
    int main()
    {
        int b = func();
        cout << b << endl;
    }

Visual Studio 代码将使用如下命令

Visual studio code will use the command as below

     g++ directory/main.cpp -o directory/main.out -g -Wall -fcolor-        diagnostics -std=c++11

此命令将引发架构 x86_64 的未定义符号"错误我可以用这个新命令修复它

this command will raise 'Undefined symbols for architecture x86_64' error I can fix it with this new command

    g++ main.cpp a.cpp -o main.out.

所以问题是如何配置这些 json 文件来修复 g++ 编译问题.而当我想使用FFMpeg等一些库时,如何正确链接FFMpeg .h文件.

So the problem is how to config these json files to fix the g++ compile issue. And when I want to use some libraries such as FFMpeg, how can I link the FFMpeg .h file correctly.

推荐答案

我让它工作的一种方法是进入你的构建任务,而不是说 "g++ ${file}",您可以将目标文件设置为编译为 "g++ ${fileDirname}/**.cpp",这将编译目录中的所有 .cpp 文件.

One way I have gotten it to work is by going into your build task, and instead of saying "g++ ${file}", instead you can set the target file to get compiled as "g++ ${fileDirname}/**.cpp" which will compile all the .cpp files in the directory.

这样,您可以对一个项目使用相同的构建任务,在该项目中,您可能在不同的文件夹中有多个程序,所有程序都在同一个伞形目录下.

This way you can use the same build task for a project where you may have multiple programs in different folders, all under the same umbrella directory.

相关文章