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

164 views Asked by At

I have followed some instructions to construct Visual studio code C/C++ compile and debug environment. But MSVC compiler can only compile the selected cpp file, so the included .h file associated the cpp file can not compiled. then the terminal shows *

main.obj : LNK2019 error: reference to an unresolved external character "int __cdecl func(void)" (?func@@YAHXZ) in the main function.C:\TESTmsvc\main.exe : fatal error LNK1120: unresolved external elements: 1

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;
}
1

There are 1 answers

1
LuigiBro On

I would suggest to use CMake for larger C++ and C projects.
When using VS Code you should

  • download the extensions CMake and CMake Tools by Microsoft.
  • create a CMakeLists.txt file in your project directory and (for a simple project) enter this code into your CMakeLists.txt file:
cmake_minimum_required(VERSION 3.4)
project(PROJECT_NAME)

set(CMAKE_CXX_STANDARD 17)

add_executable(PROJECT_NAME
# add the files that need to be compiled here
src/main.cc
)
  • Press [ctrl + s] to save the file and select a build kit. For a 64x build target on a 64x computer you should select:

    Visual Studio Community 2022 Release - amd64

With CMake you can also choose if you want to compile for Release, Debug, MinSizeRel or RelWithDebInfo. To do so, press [crtl + shift + p] to open the command pallete and type in CMake: Select Variant
For Debug you might want to select the Debug build target and click the debug button in the status bar.
For Release select the Release build target and click the run button.
VS Code debugging should work automatically when compiling for debug with the debug build target.

If you really want to use VS Code's build system with a task.json you can add the following line of code to the task.json to it:
"${workspaceFolder}\\src\\*.cpp"
This piece of code basically replaces the command to compile main.cpp with the command to compile every .cpp file found in the src directory