VSCode C++ 环境搭建 (Linux)

Install extensions

  • C/C++:The C/C++ extension adds language support for C/C++ to Visual Studio Code, including features such as IntelliSense and debugging.

Using C++ on Linux in VS Code

  • In this tutorial, you will configure Visual Studio Code to use the GCC C++ compiler (g++) and GDB debugger on Linux. GCC stands for GNU Compiler Collection; GDB is the GNU debugger.

Prerequisites

  • Ensure GCC is installed
gcc -v
  • If GCC isn’t installed, run the following command to update the Ubuntu package lists. An out-of-date Linux distribution can sometimes interfere with attempts to install new packages.
sudo apt-get update
  • Next install the GNU compiler tools and the GDB debugger with this command:
sudo apt-get install build-essential gdb

Create Hello World

  • From the terminal window, create an empty folder called projects to store your VS Code projects. Then create a subfolder called helloworld, navigate into it, and open VS Code in that folder by entering the following commands:
mkdir projects
cd projects
mkdir helloworld
cd helloworld
code .	# opens VS Code in the current working folder, which becomes your "workspace"

Build helloworld.cpp (tasks.json)

  • First, add hello world source code file. It’s important to have helloworld.cpp open in the editor because the next step uses the active file in the editor for context to create the build task in the next step.
    在这里插入图片描述
  • Next, you’ll create a tasks.json file to tell VS Code how to build (compile) the program. This task will invoke the g++ compiler to create an executable file from the source code.
    • From the main menu, choose Terminal > Configure Default Build Task. A dropdown appears showing various predefined build tasks for C++ compilers. Choose C/C++: g++ build active file. This will create a tasks.json file in a .vscode folder and open it in the editor.
    • Your new tasks.json file should look similar to the JSON below. This task tells g++ to take the active file (${file}), compile it, and create an executable file in the current directory (${fileDirname}) with the same name as the active file but without an extension (${fileBasenameNoExtension}), resulting in helloworld for our example.
      • The "isDefault": true value in the group object specifies that this task will be run when you press Ctrl+Shift+B. This property is for convenience only; if you set it to false, you can still run it from the Terminal menu with Tasks: Run Build Task.
{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "shell",	// Defines whether the task is run as a process or as a command inside a shell.
			"label": "C/C++: g++ build active file",	// The task's user interface label
			"command": "/usr/bin/g++",	// The command to be executed. Can be an external program or a shell command.
			"args": [	// Arguments passed to the command when this task is invoked.
				"-g",
				"${file}",
				"-o",
				"${fileDirname}/${fileBasenameNoExtension}"
			],
			"options": {	// Additional command options
				"cwd": "${workspaceFolder}"
			},
			"problemMatcher": [	// The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.
				"$gcc"
			],
			"group": {	// Defines to which execution group this task belongs to. It supports "build" to add it to the build group and "test" to add it to the test group.
				"kind": "build",
				"isDefault": true
			},	
			"detail": "compiler: /usr/bin/g++"	// An optional description of a task that shows in the Run Task quick pick as a detail.
		}
	]
}
  • You can modify your tasks.json to build multiple C++ files by using an argument like “${workspaceFolder}/*.cpp” instead of ${file}. You can also modify the output filename by replacing “${fileDirname}/${fileBasenameNoExtension}” with a hard-coded filename (for example ‘helloworld.out’).

Running the build

  • Go back to helloworld.cpp. Your task builds the active file and you want to build helloworld.cpp.
  • To run the build task defined in tasks.json, press Ctrl+Shift+B or from the Terminal main menu choose Run Build Task.
  • When the task starts, you should see the Integrated Terminal panel appear below the source code editor. After the task completes, the terminal shows output from the compiler that indicates whether the build succeeded or failed. For a successful g++ build, the output looks something like this:
    在这里插入图片描述
  • Create a new terminal using the + button and you’ll have a terminal running your default shell with the helloworld folder as the working directory. 在这里插入图片描述

Debug helloworld.cpp (launch.json)

  • Next, you’ll create a launch.json file to configure VS Code to launch the GDB debugger when you press F5 to debug the program.
  • From the main menu, choose Run > Add Configuration… and then choose C++ (GDB/LLDB).
  • You’ll then see a dropdown for various predefined debugging configurations. Choose g++ build and debug active file.
    在这里插入图片描述
  • VS Code creates a launch.json file, opens it in the editor, and builds and runs ‘helloworld’.
    • program specifies the program you want to debug. Here it is set to the active file folder ${fileDirname} and active filename without an extension ${fileBasenameNoExtension}
    • By default, the C++ extension won’t add any breakpoints to your source code and the stopAtEntry value is set to false. Change the stopAtEntry value to true to cause the debugger to stop on the main method when you start debugging.
{
    // 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": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++ build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}

Start a debugging session

  • Go back to helloworld.cpp so that it is the active file.
  • Press F5 or from the main menu choose Run > Start Debugging.
    在这里插入图片描述
  • When the loop has completed, you can see the output in the Debug Console tab of the integrated terminal, along with some other diagnostic information that is output by GDB.
    在这里插入图片描述

Make use of Makefile

  • Makefile
helloworld: helloworld.o
	g++ -g -o helloworld helloworld.o

helloworld.o: helloworld.cpp
	g++ -g -c helloworld.cpp

clean:
	rm -rf *.o helloworld
  • tasks.json
{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "shell",	// Defines whether the task is run as a process or as a command inside a shell.
			"label": "C/C++: g++ build active file",	// The task's user interface label
			"command": "make",	// The command to be executed. Can be an external program or a shell command.
			"group": {	// Defines to which execution group this task belongs to. It supports "build" to add it to the build group and "test" to add it to the test group.
				"kind": "build",
				"isDefault": true
			},	
			"detail": "compiler: /usr/bin/g++"	// An optional description of a task that shows in the Run Task quick pick as a detail.
		}
	]
}
  • launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++ - Build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": true,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++ build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}

C/C++ configurations

  • If you want more control over the C/C++ extension, you can create a c_cpp_properties.json file, which will allow you to change settings such as the path to the compiler, include paths, C++ standard (default is C++17), and more.
{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "gcc-x64"
        }
    ],
    "version": 4
}

  • You can view the C/C++ configuration UI by running the command C/C++: Edit Configurations (UI) from the Command Palette (Ctrl+Shift+P).
    在这里插入图片描述
  • This opens the C/C++ Configurations page. When you make changes here, VS Code writes them to a file called c_cpp_properties.json in the .vscode folder.
    在这里插入图片描述
  • You only need to modify the Include path setting if your program includes header files that are not in your workspace or in the standard library path.

Using C++ on Windows in VS Code

Get started with CMake Tools on Linux

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值