- 开发
- C++源文件
- Makefile
- VSCode配置
- task
- properties
在《 VSCode+WSL开发环境》中,已经介绍了VSCode+WSL如何进行开发;本文将介绍如何使用makefile来编译C++程序。 开发
以编译子文件夹下的文件为例,目录结构如下:
源文件中,以vector为例,如何使用移动构造,以及快速清空vector:
#includeMakefile#include #include #include #include class DemoPrint { int data{0}; public: DemoPrint(int init) : data(init) { std::cout << "DemoPrint constructor " << data << std::endl; } DemoPrint(DemoPrint &&demo) : data(demo.data + 10) { std::cout << "DemoPrint move-structor " << data << std::endl; } ~DemoPrint() { std::cout << "DemoPrint destructor " << data << std::endl; } }; void vectorClearTest() { std::vector vec; vec.push_back(DemoPrint(1)); std::cout << "after push back, size:" << vec.size() << ", capacity:" << vec.capacity() << std::endl; vec = decltype(vec){}; std::cout << "after assigned, size:" << vec.size() << ", capacity:" << vec.capacity() << std::endl; vec.push_back(DemoPrint(2)); std::cout << "after re-push back, size:" << vec.size() << ", capacity:" << vec.capacity() << std::endl; (decltype(vec){}).swap(vec); std::cout << "after swapped, size:" << vec.size() << ", capacity:" << vec.capacity() << std::endl; vec.push_back(DemoPrint(3)); vec.clear(); } void weakPtrTest() { std::weak_ptr wp{}; if (wp.expired()) { std::cout << "Empty WP expired" << std::endl; } { std::shared_ptr sp(new int(1)); wp = sp; if (wp.expired()) { std::cout << "Inscope WP expired" << std::endl; } if (sp) { } } if (wp.expired()) { std::cout << "Outscope WP expired" << std::endl; } } int main() { vectorClearTest(); std::optional oi; if (!oi) { std::cout << "optional is empty" << std::endl; } oi = 12; if (oi) { std::cout << "optional value: " << oi.value() << std::endl; } sleep(10); std::cout << "main quit." << std::endl; return 0; }
VSCode启动运行时,只会调用最顶层的Makefile,为能编译子文件下的文件,需要在顶层Makefile中调用子文件夹下的Makefile。
顶层Makefile(调用子文件夹下Makefile):
subsystem: cd learning && make clean: cd learning && make clean
运行make会自动编译,而运行make clean会做清理;
子文件夹Makefile(真正编译文件):
CFLAGS=-c -Wall -std=c++17 LFLAGS = -Wall -std=c++17 CXXFLAGS = -Wall -std=c++17 hello: hello.o g++ -g -std=c++17 -o hello hello.o hello.o: hello.cpp g++ -g -std=c++17 -o hello.o -c hello.cpp clean: rm -rf hello rm -rf *.o
为保证能支持C++17,必须设定标志CXXFLAGS,否则即使g++中添加了-std=c++17也无效。
VSCode配置为例使用make编译,需要修改.vscode目录下的tasks.json文件
task默认生成的task使用g++编译,需要修改为使用make:
{ "version": "2.0.0", "tasks": [ { "label": "build", "command": "make", "type": "shell", "group": { "kind": "build", "isDefault": true } }, { "label": "clean", "command": "make", // 在shell中使用命令,如需加参数,可再添加args属性 "args": [ "clean" ], "type": "shell", "group": { "kind": "build", "isDefault": true } } ] }
同时要保证launch.json中preLaunchTask的值与此文件中label的值相同。
properties为使vscode识别C++17,需要修改c_cpp_properties.json中cppStandard:
{ "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**" ], "defines": [], "compilerPath": "/usr/bin/gcc", "cStandard": "c11", "cppStandard": "c++17", "intelliSenseMode": "linux-gcc-x64" } ], "version": 4 }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)