Search code examples
c++visual-studio-code

VS Code will not build c++ program with multiple .cpp source files


I'm trying to build a simple program that has multiple .cpp files. I'm using VS Code on Ubuntu 17.10 and using the GCC Compiler. Here's an example of what I've got (all the files are in the same folder):

main.cpp

#include "Cat.h"
int main() {
  speak();
  return 0;
}

Cat.h

#pragma once
void speak();

Cat.cpp

#include <iostream>
#include "Cat.h"
void speak() {
  std::cout << "Meow!!" << std::endl;
}

This simple program builds in both Codeblocks and Visual Studio Community 2017 no problem and I can't figure out what I need to do to make it run. This error at the bottom indicates that the Cat.cpp file is not being picked up at all. If I was to drop the definition from this Cat.cpp into the header file the program compiles and runs fine but I want to use that .cpp file.

I understand that I may need to tell VS Code where to look for the Cat.cpp file but it's strange to me that it finds the header in the same location.

tasks.json

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Build",
            "type": "shell",
            "command": "g++ -g /home/me/project/main.cpp -o Classes",
            "group": {
                "kind": "build",
                "isDefault": true,
            },
            "problemMatcher":"$gcc"
        }
    ]
}

Solution

  • Add this in tasks.json:

            "label": "g++.exe build active file",
            "args": [
                "-g",
                "${fileDirname}\\**.cpp",
                //"${fileDirname}\\**.h",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe",
            ],
    

    And add this in launch.json:

    "preLaunchTask": "g++.exe build active file"
    

    Then it will work if your sources are in separate folders.