1

I am taking a C++, intro to CS class, and we are now starting to implement data abstraction for OOP. I am required to hide the class definitions in a separate .cpp file and to use a header file. Until now, I have been using the default settings in VSCode in my Macbook pro for creating single file programs, so I decided to create a test program to make sure the compilation, include and link would work properly before creating my entire project, but now when I try to build the program, I am receiving an error. I have tried for days to resolve the problem using potential solution without success. I am hoping someone here can lead me in the right direction.

I have included the contents of the 3 test files (test.cpp, test.h and testImp.cpp), the c_cpp_properties.json, launch.json, settings.json and task.json files and the content of the error message.

Any assistance setting up VSCode to complete including header files would be greatly appreciated since I will be having more projects with this requirement.

Thank you, James.

test.cpp

#include <iostream>
#include "test.h"

using namespace std;

int main()
{
    cout << testCalculation(5, 7) << endl;
    cout << endl;
    return 0;
}

test.h

#ifndef test_h
#define test_h

int testCalculation(int, int);

#endif /* test_h */

testImp.cpp

#include "test.h"

int testCalculation(int x, int y) {
int sum = int();
    sum = x + y;
    return sum;
};

c_cpp_properties.json

    "configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${default}",
                "${workspaceFolder}/**"
            ],
            "compilerPath": "/usr/bin/g++",
            "cStandard": "c17",
            "cppStandard": "c++11",
            "intelliSenseMode": "${default}"
        }
    ],
    "version": 4
}

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++ - Build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "lldb",
            "preLaunchTask": "C/C++: g++ build active file"
        }
    ]
}

setting.json

{
    "files.associations": {
        "iostream": "cpp"
    }
}

task.json

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

ERROR

Starting build...
/usr/bin/g++ -fdiagnostics-color=always -g /Users/jamesreal/cpp/cs-2/project-1/test.cpp -o /Users/jamesreal/cpp/cs-2/project-1/test
Undefined symbols for architecture x86_64:
  "testCalculation(int, int)", referenced from:
      _main in test-5cbf98.o
ld: symbol(s) not found for architecture x86_64

clang: error: linker command failed with exit code 1 (use -v to see invocation)
JaMiT
  • 14,422
  • 4
  • 15
  • 31
J Real
  • 43
  • 5
  • 3
    Your bug is here: `"${file}",` It means that you want to build only the active file into the executable. The documentation tells you how to fix to build all of your files here: [https://code.visualstudio.com/docs/cpp/config-clang-mac#_modifying-tasksjson](https://code.visualstudio.com/docs/cpp/config-clang-mac#_modifying-tasksjson) – drescherjm Oct 05 '21 at 01:06
  • 1
    @drescherjm, I can't thank you enough. I spent a lot of time trying to resolve this. I knew the answer was in the documentation somewhere, but I had no idea where to look. I appreciate you. Thank you ,thank you, thank you. Stay well. – J Real Oct 05 '21 at 04:08
  • If you have multiple cpp files use a build tool: Make, CMake, ..... – rioV8 Oct 05 '21 at 07:58
  • 2
    Does this answer your question? [How to use visual studio code to compile multi-cpp file?](https://stackoverflow.com/questions/51720769/how-to-use-visual-studio-code-to-compile-multi-cpp-file) – drescherjm Oct 05 '21 at 13:51
  • 1
    It took me a some time to find but I believe the above link is a reasonable duplicate. – drescherjm Oct 05 '21 at 13:51
  • 1
    @drescherjm, yes, that helped. Thank you. There are a few sources in that single post that I will also review, but your first answer provided a solution. I appreciate the follow up and for providing further resources which provide a deeper look into the problem. You rock! – J Real Oct 06 '21 at 18:22

1 Answers1

-1

-1.Bro.

Your configuration files are the Only one file to build, compile and debug, NOT your wanted multiple sources files'.

0.First See

First, you were wrong in naming "settings.json" as "setting.json";

Also, you were wrong in naming "tasks.json" as "task.json".

1.Your Project

As your project Architecture test shows,

test

|

|_.vscode

|     |__c_cpp_properties.json

|     |__launch.json

|     |__settings.json

|     |__tasks.json

|__test.cpp

|__test.h

|__testImp.cpp

3.Solutions:

There are three ways to set up multiple source files build with

VSCode.

The one is to write terminal commands to "settings.json" and

"tasks.json" + "launch.json" + "c_cpp_properties.json";

The two is to write "Makefile" file via make to do that;

The three is to write "CMakeList.txt" via CMake to do that.

Now, I just share the first solution.

4.My workspace Environment with VSCode on mac

I just use Clang9.0.0 to compile, Code Runner v0.11.6 to

run program, CodeLLDB v1.4.5 to debug, C/C++ Clang Command Adopter

v0.2.4(VSCode Extension) to provide static detection with VSCode on mac.

Maybe you use cpptools(cpptools is used to debug, This CPPtools

and that CodeLLDB conflict. ), that doesn't matter, just change

"type" from "lldb" to "cppdbg" in "launch.json".

5.My solution

This is a problem about multiple source files under the same folder to compile and debug with VSCode on mac.

I always firstly config settings.json. That shows like:

"settings.json", Just watch out for the "code-runner.executorMap".

Big Notices: This is "settings.json". Not "setting.json"!!!

{
    "files.defaultLanguage": "c++",
    "editor.suggest.snippetsPreventQuickSuggestions": false,
    "editor.acceptSuggestionOnEnter": "off",
    "code-runner.runInTerminal": true,
    "code-runner.executorMap": {
    // 3.Mutiple sourece C/C++ files under same folder build, compile, debug...
    // if put main.o and debug folder into the current directory "./"
    "c": "cd $dir && clang -std=c11 -stdlib=libc++  $dir/*.c  -o $dir/$fileNameWithoutExt && $dir/$fileNameWithoutExt", // Have changed
    "cpp": "cd $dir && clang++ -std=c++11 -stdlib=libc++  $dir/*.cpp -o $dir/$fileNameWithoutExt && $dir/$fileNameWithoutExt" // Have changed
    },
    "code-runner.saveFileBeforeRun": true,
    "code-runner.preserveFocus": false,
    "code-runner.clearPreviousOutput": false,
    "code-runner.ignoreSelection": true,
    "C_Cpp.clang_format_sortIncludes": true,
    "editor.formatOnType": true,
    "clang.cxxflags": [
        "-std=c++11"
    ],
    "clang.cflags": [
        "-std=c11"
    ],
    "C_Cpp.updateChannel": "Insiders",
    "[makefile]": {
        "editor.insertSpaces": true
    },
    "C_Cpp.default.includePath": [
        "${workspaceFolder}"
    ],
    "clang.completion.enable": true
}

If you use gcc/g++, just change the clang/clang++ to those.

If this line code needs to change or function, I add the comment

"// Have changed". Just notices that line code! Please!

"tasks.json": You know, that's "tasks.json"!!! NOT "task.json".

{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "shell",
      "label": "Compile With clang++",
      //"command": "clang++",/usr/bin/clang++
      "command": "/usr/bin/clang++",
      "args": [
        "-std=c++11",
        "-stdlib=libc++",
        // My project fitBodyBootCamp were under 
        // /Users/marryme/VSCode/CppProject/fitBodyBootCamp
        // So ${workspcaeFolder} also were
        // /Users/marryme/VSCode/CppProject/fitBodyBootCamp
        // all the *.cpp files were under
        // /Users/marryme/VSCode/CppProject/fitBodyBootCamp
        "${workspaceFolder}/*.cpp", // Have changed
        "-o",
        // Thanks those chiense website bloggers!
        // 1.mac vscode compile c++ multi-directory code demo
        // https://blog.csdn.net/fangfengzhen115/article/details/121496770?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-4.pc_relevant_default&spm=1001.2101.3001.4242.3&utm_relevant_index=7
        // 2.Compile and debug c++ multi-folder project under VSCode (non-makefile)
        // https://blog.csdn.net/BaiRuichang/article/details/106463035
        // I also put the main.o under my current workspace directory
        // This after "-o"  is the target file test.o or test.out or test
        "${workspaceFolder}/${fileBasenameNoExtension}", // Have changed
        "-I",
        // This after "-I" if the include files directory
        "${workspaceFolder}", // Have changed
        "-Wall",
        "-g"
      ],
      "options": {
        // "cwd" is the source files directory
        "cwd": "${workspaceFolder}" // Have changed
      },
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

"launch.json":

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug With LLDB",
      "type": "lldb",
      "request": "launch",
      // "program" is the target file diretory
      "program": "${workspaceFolder}/${fileBasenameNoExtension}", // Have changed
      "args": [],
      "stopAtEntry": true,
      //"cwd": "${workspaceFolder}/../build",// Have changed
      //"cwd": "${fileDirName}", ${workspaceFolder}/../build
      // Changes the current working directory directive ("cwd") to the folder
      // where main.cpp is.
      // This "cwd" is the same as "cwd" in the tasks.json 
      // That's the source files directory
      "cwd": "${workspaceFolder}", // Have changed
      "environment": [],
      "externalConsole": false,
      "preLaunchTask": "Compile With clang++"
    }
  ]
}

Now, "c_cpp_properties.json"

{
  "configurations": [
    {
      "name": "Mac",
      "includePath": [
        // This is the include files directory
        "${workspaceFolder}/**", // Have Change
        "/Library/Developer/CommandLineTools/usr/include",
        "/Library/Developer/CommandLineTools/usr/lib/clang/9.0.0/include",
        "/usr/local/include",
        "/Library/Developer/CommandLineTools/usr/include/c++/v1",
        "/usr/include"
      ],
      "defines": [],
      "macFrameworkPath": [
        "/System/Library/Frameworks",
        "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks",
        "/Library/Frameworks"
      ],
      "compilerPath": "/usr/bin/clang",
      "cStandard": "c11",
      "cppStandard": "c++11",
      "intelliSenseMode": "clang-x64"
    }
  ],
  "version": 4
}

Notices:

You only need to modify the Include path setting if your program includes

header files that are not in your workspace or the standard library path.

Especially: "includePath": [ "/Library/Developer/CommandLineTools/usr/lib/clang/9.0.0/include"].

If your separated Command-line tools's Clang version is 9.0.0, copy this program

directly.

If not, just use this command to checkout the Clang version of your separated

Command-line tools:

cd /Library/Developer/CommandLineTools/usr/lib/clang/ && ls

That may show like this: 9.0.0 or 9.1.0 or 10.0.0 or X.X.X. As this may show,

The Clang version of your separated Command-line tools is 9.0.0, or 9.0.1 or

10.0.0 or X.X.X. And just replace my 9.0.0.

If you do not have a separated Command-line tool, just install a separated command

line tools for your Mac depending on your macOS system.

I will add the 5 files via adding the file.

END.

Finally,

If you need to build separated multiple source files,

that architecture just likes:

fitBody

|

|_.vscode

|     |__c_cpp_properties.json

|     |__launch.json

|     |__settings.json

|     |__tasks.json

|__build

|__inc

|     |__fitbody.h

|__src

     |__fitbody.cpp
 
     |__main.cpp

Please just make reference to Separated Multiple CXX Manually VScode(mac) from GitHub Gist.

Or, make reference to Separated Multiple CXX Manually VScode(mac) from GitHub.

Vittore Marcas
  • 1,007
  • 8
  • 11