1. 程式人生 > 其它 >VSCode 使用Cmake對C++進行多檔案編譯(windows)

VSCode 使用Cmake對C++進行多檔案編譯(windows)

技術標籤:C++vscodec++

VSCode和mingw的安裝就不介紹了,VSCode對單檔案編譯十分友好,但如果編寫多檔案專案的話,就比較複雜。
基本上有兩種方式支援多檔案編譯

1.單純使用g++命令(不太流行,但不需要安裝外掛)

g++ -g main.c 其它檔案.c -o out.exe` 

2.使用CMAKE(推薦)

Cmake和mingw安裝網址如下:

連結: https://pan.baidu.com/s/1rgPcvq1ePNn44FiQk_tN9w 
提取碼: g69w

把CMAKE檔案下載後解壓,並新增路徑(到bin目錄止) 同時在VSCode中安裝外掛: CMAKE 和 CMAKETools

在這裡插入圖片描述
tasks.json:

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "cppbuild",
			"label": "C/C++: g++.exe build active file",
			"command": "D:\\Code\\C++\\cfg\\mingw64\\bin\\g++.exe",
			//command需更改為自己的mingw目錄
			"args"
: [ "-g", //"${file}",//單檔案編譯 "${fileDirname}\\*.cpp",//多檔案編譯 "-o", "${fileDirname}\\out.exe" ], "options": { "cwd": "${workspaceFolder}" }, "problemMatcher": [ "$gcc"
], "group": "build", "detail": "compiler: D:\\Code\\C++\\cfg\\mingw64\\bin\\g++.exe" //需更改為自己的mingw目錄 } ] }

launch.json

{
    // 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++.exe - 生成和除錯活動檔案",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}\\out.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "D:\\Code\\C++\\cfg\\mingw64\\bin\\gdb.exe",
            //需更改為自己目錄
            "setupCommands": [
                {
                    "description": "為 gdb 啟用整齊列印",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++.exe build active file"
        }
    ]
}

詳細教程也可參考視訊

https://www.bilibili.com/video/BV13K411M78v?p=2

值得一提的是 在程式設計時 自己編寫的.h檔案使用相對路徑必須用引號。
還有 以上步驟是使用F5(如果鍵盤已經對F5鍵盤有預設操作,則Fn+F5)執行除錯才可,如果是安裝了Code Runner外掛一鍵執行時還是隻能單檔案編譯,可通過更改其預設命令 使用g++ -g main.c 其它檔案.c -o out.exe 的形式。
如果還不懂的話 可評論或私信。