Software tools teaches you how to use Visual Studio Code to develop C/C++(Linux)

There are many C/C + + development tools. Microsoft's Visual Studio and QT are good choices, but these ides are too large, and many ides are charged. The author here recommends the way of GCC+Make + code editor to develop C?C + +, which is not only suitable for PC, but also for embedded.

Let's talk about the software we need.

(1) VSCode: a super easy-to-use editor that supports syntax highlighting, intelligent code completion, custom hotkeys, bracket matching, code snippets, code comparison Diff, Git and other features of almost all mainstream development languages, supports plug-in expansion, and is optimized for web page development and cloud application development. The software supports Win, Mac and Linux across platforms and runs smoothly. It can be said to be the work of Microsoft's conscience, which is also the focus of this article.

(2) GCC: GCC is the official compiler of GNU operating system. It has been adopted as a standard compiler by most Unix like operating systems. GCC only means GNU C Compiler. After so many years of development, GCC can not only support c language; It now also supports Ada language, C + + language, Java language, Objective C language, Pascal language, COBOL language, Mercury language supporting functional programming and logic programming, and so on. GCC is no longer just the meaning of GNU C language compiler, but has become the meaning of GNU Compiler Collection, that is, the GNU compiler family. On the other hand, when it comes to GCC's support for operating system platform and hardware platform, it can be summarized in one sentence: ubiquitous.

(3) make: the make tool is used to simplify the compilation process. When compiling a large project including hundreds of files, file by file compilation is cumbersome and inefficient, and it needs to be recompiled after updating a file. Makefile files are created to solve such problems. At present, most ides, including VS under Window, use makefile files, which are only automatically generated by the system and can't be felt by programmers. The key to the use of make tool is to write makefile files.

The above software is open source and free. You can play it!

1 Visual Studio Code installation

1. According to the operating system used, download and install the latest version directly from the official website of Visual Studio Code.

Download address

The installation is very simple. Code_ 1.59.1-1629375198_ Copy amd64.deb to Ubuntu.

$ sudo dpkg -i code_1.59.1-1629375198_amd64.deb

After installation, there is a Visual Studio Code shortcut file in the folder / usr/share/applications. You can drag it to the sidebar to open the software in the shortcut.

The opening interface is as follows:

2. Open VS Code, click the "Extensions" icon, search for C/C + + plug-ins (provided by Microsoft), and click Install.

3. Install the Chinese plug-in.

Restart the application. Visual Studio Code is the Chinese interface.
If necessary, you can install the compiler that comes with VS Code.


2 compilation tool installation

The previously installed Visual Studio Code can only be said to be a code editor. Compiling code requires a compiler. The compiler for Linux system is GCC. The installation commands are as follows:

$ sudo apt-get install gcc

Then enter the following command in the command window to verify that the installation was successful:

$ gcc -v 

For a single file, GCC compilation is OK, but for large projects, Makefile needs to be written to manage the project, which requires a tool to identify Makefile files, that is, make tool.

Before installing the make tool, let's see what a makefile is? Makefile can be simply regarded as the Compilation Rules of a project file, which describes the compilation and linking rules of the whole project. It includes those files that need to be compiled, those files that do not need to be compiled, those files that need to be compiled first, those files that need to be compiled later, those files that need to be rebuilt, etc. Everything involved in compiling the whole project can be described in makefile. In other words, makefile can automate the compilation of our project without manually entering a pile of source files and parameters every time.

Installing make on Linux is easy. You can use apt get.

$ sudo apt-get install make

After installation, you can view the version information of make.


3 developing C/C with Visual Studio Code++

3.1 create a new project

Select a folder and leave it blank. Then select the folder in VS Code.

The final project created is as follows:

3.2 configuration Engineering

The next step is configuration engineering.

Configuration c_cpp_properties.json

c_ cpp_ The function of properties is to configure the intelligent syntax auxiliary function of code.

Open c_cpp_properties.json configuration file, enter the following:

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "/usr/include",
                "${workspaceFolder}"
            ],
            "defines": [
                
            ],
            "compilerPath": "/usr/bin/gcc",
            "intelliSenseMode": "gcc-x64",
            "browse": {
                "limitSymbolsToIncludedHeaders": true,
                "databaseFilename": "",
                "path": [
                    "${workspaceFolder}"
                ]
            }
        }
    ],
    "version": 4
}

name: This is the label used to mark the platform used. In addition to Linux, you can also choose Win32 or Mac. In other words, three groups of configurations can be written under "configuration" in this json. As long as different platforms are written in front of each group of configurations, they can be used on different operating systems, and different configurations will be automatically adapted.

includePath: header file path. The first directory is the directory of C language standard library. The remaining directories can be copied directly from Makefile and modified slightly. "${workspaceFolder}" indicates the project folder;

Definitions: global macro definitions. The macro definitions here are only written in the source code. VS Code is just an editor. It does not read the makefile when checking the code, so some macro definitions need to be configured by itself.

compilerPath: the path to the compiler.

IntelliSense mode: because I use GCC, I choose gcc-x64.

browse: source file search path. It is used for code completion and search definition. This path is different from includePath. browse.path automatically recurses all subdirectories. include.path only looks at this directory by default.

c_cpp_properties configuration description

Configure tasks.json

The tasks.json file is used to configure the compilation task. If not, you need to create the tasks.json file, as follows:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "build",
            "command": "gcc",
            "args": [
              "-g",
              "${file}",
              "-o",
              "${fileDirname}/{fileBasenameNoExtension}"
            ],
            "problemMatcher": "$gcc",
            "options": {
              "cwd": "${workspaceFolder}"
            },
            "group": {
              "kind": "build",
              "isDefault": true
            }
        }
    ]
}

Type: task type. The task executes shell commands.
label: task name. This is the name used in the launch.json call. Note that it is case sensitive.
Command: the execution command of the task, which is gcc.
args: the parameters of the task. That is, the parameters carried by the execution command. That is, the parameters carried by the above command gcc.
problemMatcher: error capture. gcc is used here to capture errors.

Tasks configuration description

Configure launch.json

Create a launch.json file in the vscode folder, which is the entry file for debugging. The contents are as follows:

{
    "version": "0.2.0",
    "configurations": [
        {
          "name": "gcc.exe - Build and debug active file",
          "type": "cppdbg",
          "request": "launch",
          "program": "${fileDirname}/${fileBasenameNoExtension}",
          "args": [],
          "stopAtEntry": false,
          "cwd": "${workspaceFolder}",
          "environment": [],
          "externalConsole": false,
          "MIMode": "gdb",
          "miDebuggerPath": "gdb",
          "setupCommands": [
            {
              "description": "by gdb Enable neat printing",
              "text": "-enable-pretty-printing",
              "ignoreFailures": true
            }
          ],
          "preLaunchTask": "build"
        }
      ]
}  

Name: name of debugging.
Type: debugging type, except for debugging with msvc
request: you can choose launch or attach. Launch means that the program is executed at the same time when debugging is started; attcah means that the program is already running, and then debugging is started.
Program: Specifies the location of the C/C + + program.
cwd: specify the working directory.
preLaunchTask: a pre executed task before starting debugging.

launch.json reference

3.3 commissioning

Directly press F5 to enter the debugging interface. The debugging interface is as follows:

The variable window and call stack can be seen on the left side of the interface. In the middle of the window are the buttons for step-by-step debugging. There's nothing to say about this. Go and play quickly.

In addition to using the debugging tools provided with Visual Studio Code, you can also use MinGW's GDB for debugging. GDB is also a part of GNU Project, which is the same as debugging on Linux.

Common GDB commands are shown in table.

First, using gcc to compile code, you need to add '-g' parameter, which is the same as debugging in Linux.

Type "l"(list) in gdb to view the loaded file, as shown below.

For the use of GDB, please see the author's article:
GDB debugging

3.4 multi file compilation and debugging

The previous projects are single file. In actual projects, there will be many files and even many folders.

The author creates new main.c, fun.c and fun.h files here. The contents of the documents are as follows.
[main.c]

/**
  ******************************************************************************
  * @file                main.c
  * @author              BruceOu
  * @version             V1.0
  * @date                2021-09-06
  * @blog                https://blog.bruceou.cn/
  * @Official Accounts   Embedded experimental building
  * @brief               
  ******************************************************************************
  */
/**Include*********************************************************************/
#include "fun.h"

/**
  * @brief  main
  * @param  None
  * @retval int
  */
int main()
{
    int num = 100;

    fun_print_int(num);

    return 0;
}

[fun.c]

/**
  ******************************************************************************
  * @file                fun.c
  * @author              BruceOu
  * @version             V1.0
  * @date                2021-09-06
  * @blog                https://blog.bruceou.cn/
  * @Official Accounts   Embedded experimental building
  * @brief               fun
  ******************************************************************************
  */
/**Include**********************************************************************/
#include "fun.h"

/**
  * @brief  print number
  * @param  num
  * @retval None
  */
void fun_print_int(int num)
{
    printf("fun print int: %d\n", num);
}

[fun.h]

#ifndef _FUN_H_
#define _FUN_H_

#include "stdio.h"

void fun_print_int(int num);

#endif

If you encounter multiple files, you need to include the xxx.h file and xxx.c source file contained in main.c into the GCC compilation parameters, that is, the tasks.json file.
[tasks.json]

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "build",
            "command": "gcc",
            "args": [
              "-g",
              "${file}",
              "${fileDirname}/fun.c",
              "-o",
              "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "problemMatcher": "$gcc",
            "options": {
              "cwd": "${workspaceFolder}"
            },
            "group": {
              "kind": "build",
              "isDefault": true
            }
        }
    ]
}

As you can see, compared with a single file, the configuration of multiple files is to add related dependent files in the args parameter.

Next, debug.

From the debugging results, there is no problem at all.

However, if there are many files, this method is obviously not universal in other environments. Here, you need to use Makefile to manage project files.

[Makefile]

##Compiler tool
CC = gcc

##del is required for Windows platform deletion
win = 

TARGET = main
SOURCE = *.c

#
CPPFLAGS = -I.
CFLAGS = -g -Wall -o2

obj:
    $(CC) $(CPPFLAGS) $(CFLAGS) -o $(TARGET) $(SOURCE)

## clean
clean:
ifdef win
    del $(TARGET).exe
else
    rm  $(TARGET)
endif

.PHONY: clean

It is worth noting that in makefile, the command line should start with tab key. In windows and linux, it may be due to different editors. Note here, or an error of 'missing separator. Stop' may be reported.

To debug using Visual Studio Code, you also need to modify the tasks.json file.
[tasks.json]

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "build",
            "command": "make",
            "args": [
              "-j4"
            ],
            "dependsOn":"clean"
        },
        {
          "type": "shell",
          "label": "clean",
          "command": "make",
          "args": [
            "clean"
          ]
      }
    ]
}

tasks.json creates two new tasks, one is the make task and the other is the clean task. The make task depends on clean. Before each debugging, you need to clean up the results of the previous compilation.

It can also be debugged.

Of course, you can also use GDB debugging.

Of course, cmake can also be used here to manage projects. Those who are interested can study it.


Welcome to my website

Bruce Ou's beep beep beep
Bruce Ou's home page
Bruce Ou's blog
Bruce Ou's CSDN blog
Bruce Ou's short book
What does Bruce ou know

Welcome to subscribe to my WeChat official account.

Tags: Linux Visual Studio Code

Posted on Fri, 01 Oct 2021 16:50:07 -0400 by Bookmark