How to use visual studio code to compile multi-cpp file?

為{幸葍}努か 提交于 2020-01-05 07:08:07

问题


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:

the a.h file

    int func();

the a.cpp file

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

the main.cpp file

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

Visual studio code will use the command as below

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

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.

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.


回答1:


For very simple projects you can simply pass multiple cpp files to the compiler in a single command, e.g:

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

You can simply change your compile command in tasks.json to this value.

However as your project grows you will find this approach causes you more and more problems. I'd recommend you look into a proper build system, there are many to choose from including:

  • Make - the main standard build system on Linux but difficult to learn and fiddly
  • CMake - visual studio code has some support for cmake
  • Gyp - can generate make files
  • Scons - python like build scripts



回答2:


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.



来源:https://stackoverflow.com/questions/51720769/how-to-use-visual-studio-code-to-compile-multi-cpp-file

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