Using vs code to compile debugging C + + project in Linux _c language

Source: Internet
Author: User
Tags centos

Objective

About vs code under Linux Installation here is not mentioned, whether it is CentOS or Ubuntu, if you do not understand and search the problem enough, you will solve.

First, the predecessor Knowledge--gcc/g++ compile link process

Under Windows, if you are developing with Visual Studio, the C + + compiler typically uses MSBuild, which is provided by Microsoft, and in Linux C + + compilers are mostly gcc/g++. Since the development of C + + under Linux, it is necessary to understand some of the basic knowledge of the g++ compiler.

Suppose I now have one of the simplest C + + files:

 #include <iostream>
 using namespace std;
 int main () {
 cout << "Hello, World!!!!" << Endl;
 return 0;
 }

How do you compile it next? In simple terms, it's two steps: Compile first, then link

1. Install the g++ compiler

Start terminal, enter root mode, install GCC and g++

Ubuntu:

Centos:

[Xxx@xxx ~]$ su
[xxx@xxx ~]# yum install gcc
[xxx@xxx ~]# gcc--version
[xxx@xxx ~]# yum Install] Gcc-g++
   [xxx@xxx ~]# g++--version

2. Compile Hello.cpp

[Xxx@xxx ~]$ g++-C hello.cpp

The output is a hello.o file, which is the intermediate file generated by the compilation process. -c means compile only, not link.

3. Link hello.o generation 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 that was generated in the previous step.

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

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

However, the 2nd and 3 steps are meaningful to perform separately, as will be mentioned later.

4. Run Hello.out

Finally, perform the following hello.out to verify the output.

[Xxx@xxx ~]$./hello.out

Second, the construction project

The actual development process is certainly not the only one CPP so simple, sometimes there will be a lot of. h and. cpp files to match, then the above directly through the g++ to compile the executable file is not so easy. We need to help build and organize project code by making this powerful project building tool.

Suppose there are now 3 files: hw2.cpp, Solution.h and Solution.cpp

 /* Solution.h
 /class Solution {public
 :
 void Say ();
 
/* Solution.cpp *
 /#include <iostream>
 #include "solution.h"
 void Solution::say () {
 std::cout << "hi!" << Std::endl;
 }
 /* hw2.cpp
 /* #include "solution.h"
 int main () {
 solution sln;
 SLn. Say ();
 return 0;
 }

You can see that this simple example includes header file references, definitions, and implementation separations, and if you directly g++-o hw2.out hw2.cpp will report an error that does not define the reference:

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

/TMP/CCIMYTXF.O: In function ' main ':

Hw2.cpp: (. text+0x10): References not defined for ' Solution::say () '

COLLECT2: Error: LD return 1

Now it's time to make a point.

First of all, we need to know about makefile.

Create a makefile file in the root directory of your project to tell make how to compile and link the program.

BUILD:HW2.O solution.o
 g++-o build hw2.o solution.o #注意前面必须是tab, can not be a space, hw2.o:hw2.cpp solution.h g++-g-c
 Hw2.cpp
 solution.o:solution.h solution.cpp
 g++-g-c solution.cpp clean
 :
 rm hw2.o SOLUTION.O Build

Let's first explain the basic grammatical rules of makefile:

Target ...: Prerequisites
... Command #注意前面是tab

Target is an object file, it can be object files, or it can be an executable file, or it can be a label;

Prerequisites is the file or target that is needed to generate that target;

command is what you need to execute (any shell command).

That's the target. One or more targets, depending on the files in the prerequisites list, have their execution rules defined in the command. If the file in the prerequisites list is newer than target, the command is executed, otherwise it is skipped. This is the rationale for the entire make process.

So, looking back at the makefile file defined above, let's explain how each of the two lines works

 BUILD:HW2.O solution.o
 g++-O build hw2.o solution.o

Target is build, dependent on HW2.O and SOLUTION.O, and the command executed is g++-O build hw2.o solution.o

It means that by g++ link hw2.o and SOLUTION.O, the executable file is generated build,prerequisites there are two. o files, because HW2 is referenced in the code.

Hw2.o:hw2.cpp solution.h
 g++-g-c hw2.cpp

Target is HW2.O, dependent on hw2.cpp and solution.h, execution command is g++-g-c hw2.cpp

The meaning is to compile the Hw2.cpp file by g++, generate the hw2.o file, the g++ command in-G indicates that the generated file is debug, and if not-G, the breakpoint cannot be killed when debugging.

 Solution.o:solution.h solution.cpp
 g++-g-c solution.cpp

Ditto, compile Solution.cpp file, generate SOLUTION.O file.

Clean:
 rm hw2.o SOLUTION.O Build

Clean here is not an executable file, it is not an. o file, it is just an action name, similar to the role of label, make does not look for the dependencies after the colon, and does not automatically execute the command. If you want to execute this command, you must display the name of the entire action after make, such as get clean.

OK, next, let's talk about how make works. In the default manner, we simply enter make, and the following behavior occurs:

A. Make to find a file named Makefile or makefile in the current directory;

B. If found, it will look for the first target in the file, such as the build in the above file, and as the ultimate target file;

C. If the file for the first target does not exist, or if its dependent. o file is modified more than the target file, the next command is executed to generate the target file;

D. If the. o file that the first target relies on does not exist, then the dependency of target. O is found in the makefile file, and if found then the execution command,.o dependency must be. h or. cpp, so make can generate the. o file.

E. Back to step b to implement the final goal

Look at the execution results.

[Xxx@xxx ~]$ make
g++-g-c hw2.cpp g++-g-c solution.cpp g++
-o build hw2.o solution.o #注意前面必须是tab, cannot be a space 
   
    [xxx@xxx ~]$./build 
hi!
[Xxx@xxx ~]$
   

Because the makefile file has the option of-G, it can be debugged through GDB, and will kill the point of interruption, here is interested to know more about the use of GDB.

Next we'll talk about how to debug with VS code.

Third, compile and debug in VS code

After you install the VS code First, you need to install the extended cpptools, please do it yourself.

Click the menu to view-> debugging, or direct shortcut CTRL + SHIFT + D

Clicking on the settings icon and selecting C + + (GDB/LLDB) in the pop-up selection environment automatically creates a Launch.json file

As the name suggests, Laucn.json's role is to tell vs code how to perform the startup task, which is what file we want to start up, in the example above is obviously the build of the executable file. Modify the program node of the wavy line in the JSON file, change it to ${workspaceroot}/build, and the rest of it is temporarily unchanged.

 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": [], "Stopa
Tentry ": false, One" CWD ":" ${workspaceroot} "," Environment ": []," externalconsole ": True," Linux ": {
"Mimode": "GdB", "OS X": {"Mimode": "Lldb"}, "Windows": {"Mimode": "GdB" {"Name": "C + + Attach", "type": "cppdbg", "Request": "Attach", "program": "${    Workspaceroot}/build "," ProcessID ":" ${command.pickprocess} "," Linux ": {to" Mimode ":" GdB "32}, 33 "OS X": {"Mimode": "Lldb"}, "Windows": {Panax Notoginseng "Mimode": "GdB" "}" [

Then we try F5 and start debugging, and we can see the error of reporting a missing build file. The reason is that we haven't executed make to compile the executable file yet. In the Launch.json file, we add a prelaunchtask node and set the value to "build". Notice that the build here does not refer to the executable build, but to 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": [],
"    stopatentry": false, one    "CWD": "${workspaceroot}",    " Environment ": [],
"    externalconsole ": True,    " prelaunchtask ":" Build ",    " Linux ": {
"     mimode ":" GdB "    },    " OS X ": {"     Mimode ":" Lldb "
20 "    Windows": {"Mimode"     : "GdB"}   ,   {
"    name": "C + + Attach", "    type": "cppdbg",
"    request": "Attach",    "Program": "${workspaceroot}/build",
"    ProcessID": "${command.pickprocess}",    "Linux": {
"     Mimode": "GdB"
, "    OS X": {"Mimode"     : "Lldb"    },
Notoginseng    "Windows": {
"     mimode": "GdB"}
42}

If you try F5 again, you will be prompted with a message:

Click on the configuration task to run the program, and select others, will automatically generate a Tasks.json file, the role of this file is to tell launch or compiler needs to perform what action. Obviously we're going to execute the make command here, 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   {
ten    "TaskName": "Build",
one    "Problemmatcher": {
"     owner": "CPP",     "filelocation": ["Relative", "${ Workspaceroot} "],     " pattern ": {      " regexp ":" ^ (. *):(\\d+):(\\d+): \\s+ (warning|error): \\s+ (. *) $ ",
"      file ": 1,
" line      ": 2,      " column ": 3,      " severity ": 4,      "message": 5}
}
25}

Where the Tasks node is a set of tasks, notice one of the tasks named Build, This is the prelaunchtask specified in the Launch.json file, which indicates that before you start the executable program, you will perform the build task Prelaunchtask here, re-make the code, update the executable program, and then start.

Of course, you can also refer to running tasks without starting the executable program, direct CTRL + SHIFT + B, in the VSC console can see the same output as the terminal execution:

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

On the meaning of more nodes in the Launch.json and Tasks.json of VS Code, reference

Https://code.visualstudio.com/docs/editor/debugging

Https://code.visualstudio.com/docs/editor/tasks

After setting the breakpoint, F5, you can go to the breakpoint debugging

Summarize

This article mainly summarizes the basic knowledge of gcc/g++ and Make/makefile, as well as using vs code for debugging and development under Linux, hope to help the students who are digging the pit, if you have any questions, we can exchange messages, thank you for your support to the cloud-dwelling community.

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: info-contact@alibabacloud.com 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.