在这个网站下载最新版的 MinGW 编译器
https://sourceforge.net/projects/mingw/
下载好后按continue
按Apply
装完之后按Close
设置环境变数
在电脑上按右键->内容->进阶系统设定->环境变数
设好之后重新开启VS code,更改才会生效
开启VS code->档案->开启资料夹
接着安装VS code的c/c++延伸模组
安装C/C++ Clang Command Adapter让VS code可以有语法错误提示和完整的程式码自动完成功能
安装code runner
接着新增一个.c档随便打个C程式
结果右下角会出现错误叫你必须安装Clang
到这个网站下载Clang
http://releases.llvm.org/download.html
选择Download LLVM 8.0.0的Windows (64-bit)
下载完毕后执行LLVM-8.0.0-win64.exe
等候一阵子后
下一步
我同意
选这个把它加入环境变数,下一步
接着就一直下一步然后完成安装
装好后可以开一下进阶系统设定看一下环境变数是否有加进去
我的路径是C:\Program Files\LLVM\bin
重开VS code
新建.vscode资料夹
在里头新建settings.json
输入程式码
{ "[cpp]": { "editor.formatOnType": true, "editor.formatOnSave": true, "editor.renderIndentGuides": true, "editor.insertSpaces": true, "editor.detectIndentation": true, "editor.tabSize": 4 }, "[c]":{ "editor.formatOnType": true, "editor.formatOnSave": true, "editor.renderIndentGuides": true, "editor.insertSpaces": true, "editor.detectIndentation": true, "editor.tabSize": 4 }, "clang.executable" : "C:\\Program Files\\LLVM\\bin\\clang.exe", "clang.cxxflags": [ "-std=c++17", // <-c++程式改这里 "-IC:\\MinGW\\include", "-IC:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include", "-IC:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include\\c++", "-I${workspaceRoot}\\include", "-I${cwd}" ], "clang.cflags":[ "-std=c11", // <-c程式改这里 "-IC:\\MinGW\\include", "-IC:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include", "-I${workspaceRoot}\\include", "-I${cwd}" ], "files.associations": { "iostream": "cpp", "stdio.h": "c" }, "code-runner.runInTerminal": true, "code-runner.executorMap":{ "c": "cd $dir && gcc $fileName -o $fileNameWithoutExt -std=c11 && $dir$fileNameWithoutExt", // <-c程式改这里 "cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt -std=c++17 && $dir$fileNameWithoutExt", // <-c++程式改这里 }}
大功告成,可以新增档案开始写程式了
右键->run code或按右上角的三角形即可
如果要更改c或c++程式的版本,更改我注解的地方
譬如c程式要使用c99,就改为-std=c99
c++程式要使用c++11,就改为-std=c++11
执行程式时如果要link另外一个.c或.cpp档
就把要link的档案加在-o前面
譬如main.cpp要跟test.cpp做link
"cpp": "cd $dir && g++ $fileName test.cpp -o $fileNameWithoutExt -std=c++17 && $dir$fileNameWithoutExt"
写物件导向时这里要注意一下~
喔对了这一行
"code-runner.runInTerminal": true
是让程式在终端机中执行
你也可以改成false让程式在"输出"这一栏里执行,可以看到return code方便除错
不过缺点是不能scanf或cin输入内容
建议如果要输入内容就设成true在终端机中执行
如果没有要输入内容就设成false在输出栏中执行
最后记得你的路径中的所有资料夹跟档案不要含有中文等非英文字串
这会使得程式码的format失效,出现formatting failed的错误 !
设置範本
为了不要每次新增一个.c或.cpp档时就要重打程式码
安装template generator这个延伸模组
装好后,进到这个资料夹
新增档案{__name__.c}.c
#include <stdio.h>int main(){ return 0;}
以及{__name__.cpp}.cpp
#include <iostream>using namespace std;int main(){ return 0;}
回到VS code,按快捷键Ctrl+Shift+P
选这个,按Enter
选择c或cpp档,按Enter
接着输入档名,按Enter
範本档就会出现了