继上一篇安装完后,VSCode 还不能执行C++,还需要做一些设定让 VSCode 知道要使用哪一个编译器,要去哪里找标头档,和要怎么侦错。
需先在专案目录下加入.vscode
资料夹,之后的设定档都会放在此资料夹内。
1. 程式码自动完成 (IntelliSense)
在.vscode
资料夹下,加入c_cpp_properties.json
档案。我只做了Windows作业系统下的设定。
{ "configurations": [ { "name": "Win32", "includePath": [ "${workspaceRoot}", "C:\\MinGW\\include", "C:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include", "C:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include\\c++" ], "defines": [ "_DEBUG", "UNICODE", "__GNUC__=5", "__cdecl=__attribute__((__cdecl__))" ], "intelliSenseMode": "clang-x64", "browse": { "path": [ "${workspaceRoot}", "C:\\MinGW\\include", "C:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include", "C:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include\\c++" ], "limitSymbolsToIncludedHeaders": true, "databaseFilename": "" } } ], "version": 3}
这里需要注意 path 内的 C:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include\\c++
,要与安装 MinGW 的路径相符。
2. 建置 (Building)
在.vscode
资料夹下,加入tasks.json
档案。
{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "build", "type": "shell", "command": "g++", "args": [ "-g", "${file}", "-o", "${fileBasenameNoExtension}.exe" ], "group": { "kind": "build", "isDefault": true } } ]}
这里我想要让编译出来的exe档名和原始档一样,所以我在args设定:"-g", "${file}", "-o", "${fileBasenameNoExtension}.exe"
3. 侦错 (Debugging)
在.vscode
资料夹下,加入launch.json
档案。
{ "version": "0.2.0", "configurations": [ { "name": "(gdb) Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceRoot}/${fileBasenameNoExtension}.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceRoot}", "environment": [], "externalConsole": true, "MIMode": "gdb", "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "build" } ]}
program
对应执行档名称。miDebuggerPath
需与安装 MinGW 的路径相符。preLaunchTask
在侦错前要执行的task,对应 tasks.json 内的 taskName。
如果不设定 preLaunchTask 在侦错前必须先手动执行编译,等编译完后再执行侦错,使用起来不方便,设定后只需要按F5就能自动完成编译和侦错就像在使用 Visual Studio 一样 XD。
结语:
到这里已经能用 VSCode编译、执行、侦错 C++程式,不过真正使用后会发现 IntelliSense怎么好像和 Visual Studio有一段落差,而且没有语法检查功能,感觉只是进阶版的记事本 XD,所以在下一篇会继续介绍有那些套件可以让 VSCode 更好用,更像在使用 Visual Studio。
参考文章: C/C++ for VS Code (Preview)
相关文章:
[VSCode] Visual Studio Code 执行 C++ (1) - 安装 VSCode + MinGW
[VSCode] Visual Studio Code 执行 C++ (2) - IntelliSense + Building + Debugging
[VSCode] Visual Studio Code 执行 C++ (3) - 语法检查
[VSCode] Visual Studio Code 执行 C++ (4) - 範本 (Template)
[VSCode] Visual Studio Code 执行 C++ (5) - 中文乱码
[VSCode] Visual Studio Code 执行 C++ (6) - Code Runner