Use VS Code to compile and debug C ++ projects in Linux, and use linuxvs

Source: Internet
Author: User

Use VS Code to compile and debug C ++ projects in Linux, and use linuxvs

Recently, the project needs to develop C ++ related projects in Linux. After some exploration, I briefly summarized some precautions for compiling and debugging through VS Code.

The installation of VS Code in Linux is not mentioned here. Whether it is CentOS or Ubuntu, you will solve the problem if you do not understand and search for Q.

I. prerequisites-gcc/g ++ compilation link Process

In Windows, if you use Visual Studio for development, C/C ++ compilers generally use MSBuild provided by Microsoft; in Linux, most C/C ++ compilers use gcc/g ++. Since C ++ development is required in Linux, it is necessary to understand some basic knowledge about g ++ compiler.

Suppose I have the simplest C ++ file:

1 #include <iostream>2 using namespace std;3 int main() {4     cout << "Hello, world!!!!" << endl;5     return 0;6 }

How can we compile it next? Simply put, it is divided into two steps: first compile and then link

1. Install the g ++ Compiler

Start the terminal, enter the root mode, and install gcc and g ++


xxx@xxx:~$ sudo apt-get install build-essential

xxx@xxx:~$ gcc --version
xxx@xxx:~$ sudo apt-get install g++-4.8
xxx@xxx:~$ g++ --version


[xxx@xxx ~]$ su
[xxx@xxx ~]# yum install gcc
[xxx@xxx ~]# gcc --version
[xxx@xxx ~]# yum install g++
[xxx@xxx ~]# g++ --version
2. Compile hello. cpp
[xxx@xxx ~]$ g++ -c hello.cpp

The output result is a hello. o file, which is an intermediate file generated during the compilation process.-C indicates only compiling, not linking.

3. Link hello. o to generate hello. out
[xxx@xxx ~]$ g++ -o hello.out hello.o

The output result is a hello. out file, which is the final executable file.-O indicates the output file, Hello. o is the. o file generated in the previous step.

Of course, if steps 2 and 3 can be combined for execution, directly execute the command

[xxx@xxx ~]$ g++ -o hello.out hello.cpp

However, separate execution in steps 1 and 3 makes sense and will be discussed later.

4. Run hello. out.

Finally, run the following hello. out command to verify the output result.

[xxx@xxx ~]$ ./hello.out
2. Build a project

In the actual development process, of course, it is impossible to have only one cpp, sometimes there will be a lot. h and. cpp files work together, so it is not that easy to directly compile executable files through g ++. We need to use Make, a powerful project building tool, to help us build and organize the project code.

Suppose there are three files: hw2.cpp, solution. h, and solution. cpp.

1 /* solution.h */2 class Solution {3 public:4     void Say();5 };
1 /* solution.cpp */2 #include <iostream>3 #include "solution.h"4 void Solution::Say(){5    std::cout << "HI!" << std::endl;6 }
1 /* hw2.cpp */2 #include "solution.h"3 int main () {4     Solution sln;5     sln.Say();6     return 0;7 }


We can see that this simple example includes header file reference, definition, and implementation separation. If direct g ++-o hw2.out hw2.cpp is used, an error of undefined reference will be reported:

[Xxx @ xxx ~] $ G ++-o hw2.out hw2.cpp
/Tmp/ccIMYTxf. o: In the 'main' function:
Hw2.cpp :(. text + 0x10): an undefined reference to 'solution: Say ()'
Collect2: Error: ld returns 1


At this time, Make should show its skills.

First, we need to know about makefile.

Under the root directory of the projectCreate a makefile file to show Make how to compile and link the program.

1 build: hw2.o solution. o2 g ++-o build hw2.o solution. o # note that the front must be a tab, not a space 3 hw2.o: hw2.cpp solution. h4 g ++-g-c hw2.cpp5 solution. o: solution. h solution. cpp6 g ++-g-c solution. cpp7 clean: 8 rm hw2.o solution. o build


First, explain the basic syntax rules of makefile:

Target...: prerequisites... command # note that the preceding tab is

Target is a target File, which can be an Object File, an execution File, or a tag;

Prerequisites is the file or target required to generate the target;

Command is the command to be executed by make (any Shell command ).

To put it bluntlyTarget one or more targets depend on files in the prerequisites list, and their execution rules are defined in the command. If the files in the prerequisites list are newer than the target, the command is executed. Otherwise, the command is skipped. This is the basic principle of the entire make process.


Let's look back at the makefile file defined above. Let's explain the functions of each two rows.

1 build : hw2.o solution.o2     g++ -o build hw2.o solution.o

Target is build and depends on hw2.o and solution. o. The command executed is g ++-o build hw2.o solution. o.

It means to link hw2.o and solution. o through g ++ to generate an executable file build. prerequisites has two. o files because hw2 references solution. h In the code.


3 hw2.o : hw2.cpp solution.h4      g++ -g -c hw2.cpp

Target is hw2.o and depends on hw2.cpp and solution. h. The command is g ++-g-c hw2.cpp.

It means to compile the hw2.cpp file through g ++ and generate the hw2.o file. In the g ++ command,-g indicates that the generated file is debugable. If no-g exists, the breakpoint cannot be hit during debugging.


5 solution.o : solution.h solution.cpp6     g++ -g -c solution.cpp

Compile the solution. cpp file to generate the solution. o file.


7 clean :8     rm hw2.o solution.o build

Here, clean is neither an executable file nor an executable file.. To execute this command, you must display the name of the entire action after make, for example, make clean.


Now let's talk about how make works. In the default mode, you only need to input make to perform the following operations:

A. make: Find the file named makefile or Makefile in the current directory;

B. If it is found, it will find the first target in the file, such as the build in the above file, and act as the ultimate target file;

C. If the first target file does not exist, or its dependent. o file is modified later than the target file, the following command is executed to generate the target file;

D. if the first target is dependent on. if the file o does not exist, the target will be found in the makefile file. o dependency. If yes, Execute command ,. o dependencies must be. h or. cpp, so make can generate. o file

E. Go back to step B to implement the final goal


Check the execution result.

[Xxx @ xxx ~] $ Makeg ++-g-c hw2.cppg ++-g-c solution. cppg ++-o build hw2.o solution. o # note that the front must be a tab, not a space [xxx @ xxx ~] $./Build
[Xxx @ xxx ~] $


Since the makefile file has been added-G, so you can debug through gdb and hit the breakpoint.For more information about the usage of gdb.

Next we will talk about how to debug through VS Code.


Iii. Compiling and debugging in VS Code

After installing VS Code, you also need to install the extensionCpptools, Please complete it by yourself.


Click to view the menu-> debug, or press ctrl + shift + D.


Click the settings icon and select C ++ (GDB/LLDB) in the pop-up selection environment. A launch. json file is automatically created.

As the name suggests, laucn. json is used to tell VS Code how to execute the startup task, that is, what file we want to start. In the above example, it is clearly the executable file build. Modify the wavy program node in the json file$ {WorkspaceRoot}/buildAnd the rest remain unchanged for the time being.


 1 { 2     "version": "0.2.0", 3     "configurations": [ 4         { 5             "name": "C++ Launch", 6             "type": "cppdbg", 7             "request": "launch", 8             "program": "${workspaceRoot}/build", 9             "args": [],10             "stopAtEntry": false,11             "cwd": "${workspaceRoot}",12             "environment": [],13             "externalConsole": true,14             "linux": {15                 "MIMode": "gdb"16             },17             "osx": {18                 "MIMode": "lldb"19             },20             "windows": {21                 "MIMode": "gdb"22             }23         },24         {25             "name": "C++ Attach",26             "type": "cppdbg",27             "request": "attach",28             "program": "${workspaceRoot}/build",29             "processId": "${command.pickProcess}",30             "linux": {31                 "MIMode": "gdb"32             },33             "osx": {34                 "MIMode": "lldb"35             },36             "windows": {37                 "MIMode": "gdb"38             }39         }40     ]41 }

Next, let's try F5 and start debugging. The result shows that an error of missing build file is reported. The reason is that we have not executed make to compile the executable file. In the launch. json file, add a preLaunchTask node and set the value to "build ". Note that the build here is not an executable file build, but a task named build!

 1 { 2     "version": "0.2.0", 3     "configurations": [ 4         { 5             "name": "C++ Launch", 6             "type": "cppdbg", 7             "request": "launch", 8             "program": "${workspaceRoot}/build", 9             "args": [],10             "stopAtEntry": false,11             "cwd": "${workspaceRoot}",12             "environment": [],13             "externalConsole": true,14             "preLaunchTask": "build",15             "linux": {16                 "MIMode": "gdb"17             },18             "osx": {19                 "MIMode": "lldb"20             },21             "windows": {22                 "MIMode": "gdb"23             }24         },25         {26             "name": "C++ Attach",27             "type": "cppdbg",28             "request": "attach",29             "program": "${workspaceRoot}/build",30             "processId": "${command.pickProcess}",31             "linux": {32                 "MIMode": "gdb"33             },34             "osx": {35                 "MIMode": "lldb"36             },37             "windows": {38                 "MIMode": "gdb"39             }40         }41     ]42 }

If you try F5 again, a message is displayed:

Click Configure task run program and select Others to automatically generate a tasks. json file, which is used to tell launch or compiler what operations to perform. Obviously, run the make command to modify tasks. json as follows:

 1 { 2     "version": "0.1.0", 3     "command": "make", 4     "showOutput": "always", 5     "tasks": [ 6         { 7             "taskName": "clean" 8         }, 9         {10             "taskName": "build",11             "problemMatcher": {12                 "owner": "cpp",13                 "fileLocation":  ["relative", "${workspaceRoot}"],14                 "pattern": {15                     "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",16                     "file": 1,17                     "line": 2,18                     "column": 3,19                     "severity": 4,20                     "message": 521                 }22             }23         }24     ]25 }

The tasks node is a group of tasks. Note that a task named build is launch. the preLaunchTask specified in the json file indicates that, before starting the executable program, the preLaunchTask will be executed, that is, the build task here, re-make the code, update the executable program, and then start.

Of course, you can also run the tasks without starting the executable program. Press ctrl + shift + B to view the same output as that of the terminal in the VSC console:

After execution, there will be more. o and build files in the project.


For more meanings of the launch. json and tasks. json of VS Code, refer




Then, after the breakpoint is set, F5 is ready for breakpoint debugging.


Certificate --------------------------------------------------------------------------------------------------------------------------------------------------


This article summarizes the basic knowledge of gcc/g ++ and make/makefile, as well as the methods for debugging and development using VS Code in Linux, hoping to help those who are digging holes, avoid one problem.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.