Windows 上使用Visual Studio Code

前言

  为了从新上手好久没有用过的C/C++,准备在Windows10上搭建C/C++的编译,调试的环境。使用的IDE是VS Code,编译调试器用的是MinGW。

安装并搭建环境

  1. 安装VScode。

  2. 在VScode安装C/C++插件。

    image-20210124222739808

  3. 安装mingw(推荐使用MSys2&Mingw64)

    勾上需要的Package

  4. 配置mingw Path environment

    在这里插入图片描述

  5. 控制台执行gcc -v/g++ -v 确认环境变量配置正确

    E:\worktmp\opencv\build\x64>g++ -v
    Using built-in specs.
    COLLECT_GCC=g++
    COLLECT_LTO_WRAPPER=C:/Program\ Files/CodeBlocks/MinGW/bin/../libexec/gcc/x86_64-w64-mingw32/8.1.0/lto-wrapper.exe
    Target: x86_64-w64-mingw32

配置VS Code环境

  1. 创建新的项目文件夹,并且在VScode打开项目文件夹。

  2. 配置VScode C++环境。这里可以参考VScode官方说明

    点击view/command panel

    image-20210124224329665

    选择C/C++ Edit Configurations

    image-20210124224402829

    {
       "configurations": [
           {
               "name": "Win32",
               "includePath": [
                   "${workspaceFolder}/**"
               ],
               "defines": [
                   "_DEBUG",
                   "UNICODE",
                   "_UNICODE"
               ],
               "compilerPath": "C:\\Program Files\\CodeBlocks\\MinGW\\bin\\gcc.exe",
               "cStandard": "gnu18",
               "cppStandard": "gnu++14",
               "intelliSenseMode": "gcc-x64"
           }
       ],
       "version": 4
    }

Visual Studio Code 编译

编译单文件

  1. 代码演示

    #include 
    
    int main(int argc, char* argv[]) {
        std::cout<<"hello, world."<
  2. 需要在项目文件夹创建.vscode文件夹,并且创建task.json和launch.json两个配置文件。
    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 task",
            "type": "shell",
            "command": "g++",
            "args": [
                "-g",
                "-std=c++11",
                "main.cpp",
                "-o",
                "${workspaceRoot}\\${fileBasenameNoExtension}.exe"
            ],
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": [
                    "relative",
                    "${workspaceRoot}"
                ],
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            },
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

launch.json

{
"version": "0.2.0",
"configurations": [
    {
        "name": "(gdb) Launch",                
        "type": "cppdbg",                         
        "request": "launch",                        
        "targetArchitecture": "x86",                
        "program": "${workspaceRoot}\\${fileBasenameNoExtension}.exe",                 
        "miDebuggerPath":"C:\\mingw\\bin\\gdb.exe", 
        "args": [],     
        "stopAtEntry": false,                  
        "cwd": "${workspaceRoot}",                  
        "externalConsole": true,                  
        "preLaunchTask": "g++"                    
        }
]
 }
  1. 编译代码, 执行"build task"

    image-20210124225829235

  2. 运行程序

    image-20210124225852492

  3. 文件目录结构

    image-20210124225930204

  4. 执行效果

多文件编译

使用cmake作为构建工具

  1. 安装cmake并确认cmake生效

    C:\Users\kiah>cmake --version
    cmake version 3.19.3
    
    CMake suite maintained and supported by Kitware (kitware.com/cmake).
  2. 安装cmake 插件

    image-20210124230501501

    多了一个cmake的tab页面

    image-20210124233751923

  3. 快速构建cmake脚本

    快捷面板选择”CMake: Quick Start", 创建CMakeLists.txt

    image-20210124230533660

    cmake_minimum_required(VERSION 3.0.0)
    project(demo_cpp VERSION 0.1.0)
    
    add_executable(demo_cpp 
    main.cpp
    func.cpp
    )
    
    set(CPACK_PROJECT_NAME ${PROJECT_NAME})
    set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
    include(CPack)
  4. 选择开发工具, 快捷面板执行“ CMake: Select a Kit.”

    Select the kit

    [variant] 已加载一组新变量
    [kit] 已成功从 C:\Users\kiah\AppData\Local\CMakeTools\cmake-tools-kits.json 加载 2 工具包
    [main] 正在配置文件夹: test_v1 
    [main] 正在配置文件夹: test_v1 
    [driver] 正在切换到工具包: GCC 8.1.0

    成功后

    image-20210124230809996

  5. 选择"CMake:Confugre",然后执行"CMake:Build", 完成构建, 或者使用重新定义tasks.json

    {
       // See https://go.microsoft.com/fwlink/?LinkId=733558
       // for the documentation about the tasks.json format
       "version": "2.0.0",
       "tasks": [
           {
               "label": "cmake configure",
               "type": "shell",
               "command": "cmake",
               "args": [
                   "-S${workspaceRoot}/src",
                   "-B${workspaceRoot}/build",
                   "-G",
                   "MinGW Makefiles"
               ],
               "problemMatcher": {
                   "owner": "cpp",
                   "fileLocation": [
                       "relative",
                       "${workspaceRoot}"
                   ],
                   "pattern": {
                       "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                       "file": 1,
                       "line": 2,
                       "column": 3,
                       "severity": 4,
                       "message": 5
                   }
               },
               "group": {
                   "kind": "build",
                   "isDefault": true
               }
           },
           {
               "label": "cmake build",
               "type": "shell",
               "command": "cd src && cmake --build ${workspaceRoot}/build --config Debug --target all -- -j10",
               "args": [
               ],
               "problemMatcher": {
                   "owner": "cpp",
                   "fileLocation": [
                       "relative",
                       "${workspaceRoot}"
                   ],
                   "pattern": {
                       "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                       "file": 1,
                       "line": 2,
                       "column": 3,
                       "severity": 4,
                       "message": 5
                   }
               },
               "group": {
                   "kind": "build",
                   "isDefault": true
               }
           }
       ]
    }
  6. 构建完成后, 选择运行可以选择"CMake:Run"

  7. 调试添加 launch.json, 运行“Run without Debug" 或者选择”CMake:Debug"

    {
       // 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": "run",
               "type": "cppvsdbg",
               "request": "launch",
               "program": "${workspaceFolder}/build/demo_cpp.exe",
               "args": [],
               "stopAtEntry": false,
               "cwd": "${workspaceFolder}",
               "environment": [],
               "externalConsole": true
           }
       ]
    }
  8. 测试结果

    image-20210124231620493

使用过程中注意
如果出现如下错误
[main] 无法确定要使用的 CMake 生成器。请安装或配置首选生成器,或更新 settings.json、工具包配置或路径变量。 Error: 找不到任何可用的生成器。
需要在settings.json 确认添加如下设定,

    "cmake.generator": "MinGW Makefiles"

OpenCV 库使用

编译Opencv并安装

  1. 下载opencv 源码

  2. 使用cmake 构建

    image-20210125090752111

  3. 完成generate 后, 使用控制命令行目录切换到2. 步骤提到的输出构建目录

  4. 执行mingw32-make,开始构建

  5. 执行mingw32-make install 开始安装, 透过CMAKE_INSTALL_PREFIX 指定安装路径

    image-20210125091342025

    image-20210125091303086

  6. 确认对应路径install 成功

    image-20210125091428234

  7. 将install 的bin路径添加到PATH中

    e:\worktmp\opencv\build\x64\mingw>opencv_version
    4.5.1-dev

构建Opencv Demo

  1. 源码

    src\main.cpp

   #include <iostream>
   #include <opencv2/opencv.hpp>
   #include <opencv2/highgui.hpp>

   extern void say_hello();

   cv::Mat randu_mat() {
       cv::Mat mat(128, 128, CV_8UC3);
       cv::randu(mat, cv::Scalar::all(0), cv::Scalar::all(255));
       return mat;
   }

   int main(int argc, char* argv[]) {
       say_hello();
       auto mat = randu_mat();
       std::cout<<"imag empty "<<mat.empty()<<std::endl;
       cv::namedWindow("demo", 0);
       cv::imshow("demo",mat);
       cv::waitKey(33);
       system("pause");
       cv::destroyAllWindows();
       return 0;
   }
  1. 撰写Cmake

    src\CMakeLists.txt

   cmake_minimum_required(VERSION 3.0.0)
   project(demo_cpp VERSION 0.1.0)

   #SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY  "${workspaceRoot}/output")

   set(OpenCV_DIR "C:\\Program Files\ \(x86\)\\opencv")

   find_package(OpenCV REQUIRED )
   # tell the build to include the headers from OpenCV
   message(INFO "opencv include ${OpenCV_INCLUDE_DIRS}")
   include_directories( ${OpenCV_INCLUDE_DIRS} )

   add_executable(demo_cpp 
   main.cpp
   func.cpp
   )

   # tell it to link the executable target against OpenCV
   message(INFO "opencv libs ${OpenCV_LIBS}")
   target_link_libraries(demo_cpp ${OpenCV_LIBS} )

   #set(CPACK_PROJECT_NAME ${PROJECT_NAME})
   #set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
   #include(CPack)
   -- OpenCV ARCH: x64
   -- OpenCV RUNTIME: mingw
   -- OpenCV STATIC: OFF
   -- Found OpenCV 4.5.1 in C:/Program Files (x86)/opencv/x64/mingw/lib
   -- You might need to add C:/Program\ Files\ (x86)/opencv/x64/mingw/bin to your PATH to be able to run your applications.
   INFOopencv include C:/Program Files (x86)/opencv/include
   INFOopencv libs opencv_calib3d;opencv_core;opencv_dnn;opencv_features2d;opencv_flann;opencv_gapi;opencv_highgui;opencv_imgcodecs;opencv_imgproc;opencv_ml;opencv_objdetect;opencv_photo;opencv_stitching;opencv_video;opencv_videoio
   -- Configuring done
   -- Generating done
   -- Build files have been written to: E:/worktmp/visualcode/opencv/test_v1/build
  1. 设置compiler 属性

    .vscode\c_cpp_properties.json

    添加"C:\Program Files (x86)\opencv\include"到include路径

    {
       "configurations": [
           {
               "name": "Win32",
               "includePath": [
                   "${workspaceFolder}/**",
                   "C:\\Program Files (x86)\\opencv\\include",
               ],
               "defines": [
                   "_DEBUG",
                   "UNICODE",
                   "_UNICODE"
               ],
               "compilerPath": "C:\\Program Files\\CodeBlocks\\MinGW\\bin\\gcc.exe",
               "cStandard": "gnu18",
               "cppStandard": "gnu++14",
               "intelliSenseMode": "gcc-x64"
           }
       ],
       "version": 4
    }
  2. CMake:Configure、CMake:Build

    .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": "cmake configure",
               "type": "shell",
               "command": "cmake",
               "args": [
                   "-S${workspaceRoot}/src",
                   "-B${workspaceRoot}/build",
                   "-G",
                   "MinGW Makefiles"
               ],
               "problemMatcher": {
                   "owner": "cpp",
                   "fileLocation": [
                       "relative",
                       "${workspaceRoot}"
                   ],
                   "pattern": {
                       "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                       "file": 1,
                       "line": 2,
                       "column": 3,
                       "severity": 4,
                       "message": 5
                   }
               },
               "group": {
                   "kind": "build",
                   "isDefault": true
               }
           },
           {
               "label": "cmake build",
               "type": "shell",
               "command": "cd src && cmake --build ${workspaceRoot}/build --config Debug --target all -- -j10",
               "args": [
               ],
               "problemMatcher": {
                   "owner": "cpp",
                   "fileLocation": [
                       "relative",
                       "${workspaceRoot}"
                   ],
                   "pattern": {
                       "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                       "file": 1,
                       "line": 2,
                       "column": 3,
                       "severity": 4,
                       "message": 5
                   }
               },
               "group": {
                   "kind": "build",
                   "isDefault": true
               }
           },
           {
               "label": "build",
               "type": "shell",
               "command": "cd  ${workspaceRoot}/build && mingw32-make",
               "args": [
               ],
               "problemMatcher": {
                   "owner": "cpp",
                   "fileLocation": [
                       "relative",
                       "${workspaceRoot}"
                   ],
                   "pattern": {
                       "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                       "file": 1,
                       "line": 2,
                       "column": 3,
                       "severity": 4,
                       "message": 5
                   }
               },
               "group": {
                   "kind": "build",
                   "isDefault": true
               }
           }
       ]
   }

GDB 分析Windows下程序异常分析方法

程序完成后, 发现异常, 但是没有任何提示(相较linux, windows 还是有点对开发人员不太友好啊,或者是我不太熟悉), 启用gdb 打法查一下。

教程有时间再搞一下

E:\worktmp\visualcode\opencv\test_v1\build>gdb demo_cpp.exe
GNU gdb (GDB) 8.1
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-w64-mingw32".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from demo_cpp.exe...done.
(gdb) start
Temporary breakpoint 1 at 0x401688: file E:\worktmp\visualcode\opencv\test_v1\src\main.cpp, line 15.
Starting program: E:\worktmp\visualcode\opencv\test_v1\build\demo_cpp.exe 
[New Thread 14716.0x1f8c]
[New Thread 14716.0x1c28]
[New Thread 14716.0x3a1c]
[New Thread 14716.0x4144]

Thread 1 hit Temporary breakpoint 1, main (argc=1, argv=0x10320c0) at E:\worktmp\visualcode\opencv\test_v1\src\main.cpp:15
15          say_hello();
(gdb) bt
#0  main (argc=1, argv=0x10320c0) at E:\worktmp\visualcode\opencv\test_v1\src\main.cpp:15
(gdb) n
hello, world!
16          auto mat = randu_mat();
(gdb) n
17          std::cout<<"imag empty "<<mat.empty()<<std::endl;
(gdb) p mat
$1 = {flags = 1124024336, dims = 2, rows = 128, cols = 128, 
  data = 0xf42c00 "[\002O\263\064挽\b碉\032\370\317\332-窞ef\022vD覌葡拥\242\305磕(\a箧-\006\060\255\362}痁?Z\026p荮鄎衶\326#\345\006強bQv户屭\262\027+厷Le\b&T/\auE\201<e)\276\062ZH\250\155yrcO\200Z\250\114v\b?r,\317\066AH\246\003[t^?\374\350\031\021\b\246tQ\274\020\346\026w\247CQ(\f?\n A^\035tX\031j\242+\355%ELl8\uqx\372\375"..., 
  datastart = 0xf42c00 "[\002O\263\064挽\b碉\032\370\317\332-ef\022vD\242\305(\a-\006\060\255\362}Z?Z\026pq{\326#\345\006bQv\262\027+Le\b&T/\auE\201<e)\276\062ZH\250\155yrcO\200Z\250\114v\b?r,\317\066AH\246\003[t^?\374\350\031\021\b\246tQ\274\020\346\026w\247CQ(\f?\n A^\035tX\031j\242+\355%ELl8\uqx\372\375"..., 
  dataend = 0xf4ec00 "\r瓠\272\r瓠\272\r瓠\272\r\272\r\272\r\272\r\272\r\272\r\272\r\272\r\272\r\253\253\253\253\253\253\253\253\253\253\253\253", <incomplete sequence \253>, 
  datalimit = 0xf4ec00 "\r\272\r\272\r\272\r\272\r\272\r\272\r\272\r\272\r\272\r\272\r\272\r\253\253\253\253\253\253\253\253\253\253\253\253", <incomplete sequence \253>, 
  allocator = 0x0, u = 0xf4ec60, size = {p = 0x6efd38}, step = {p = 0x6efd80, buf = {384, 3}}}
(gdb) bt
#0  main (argc=1, argv=0x10320c0) at E:\worktmp\visualcode\opencv\test_v1\src\main.cpp:17
(gdb) s
imag empty 0
18          cv::namedWindow("demo", 0);
(gdb) n
19          cv::imshow("demo",mat);
(gdb) n

Thread 1 received signal SIGSEGV, Segmentation fault.
0x000000006cf59780 in cv::hal_AVX2::v_uint8x32::v_uint8x32 () from C:\Program Files (x86)\opencv\x64\mingw\bin\libopencv_imgproc451.dll

最后看到是在调用cv::imshow("demo",mat),加载libopencv_imgproc451.dll后, 发生了segment fault,内存访问问题。

也就重点关注在我们的mat是否正常上了。

直接在状态栏选择小虫子进行debug

或者直接点击小虫子

image-20210125093921575

直接会提示错误点

image-20210125093902059

问题原因找到, 就是mat 没有赋初值

修改后的代码

#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>

extern void say_hello();

cv::Mat randu_mat() {
    cv::Mat mat = cv::Mat::zeros(cv::Size(128,128), CV_8UC4);
    cv::randu(mat, cv::Scalar::all(0), cv::Scalar::all(255));
    return mat;
}

int main(int argc, char* argv[]) {
    say_hello();
    cv::Mat mat = randu_mat();
    // cv::cvtColor(mat,mat, cv::COLOR_RGBA2BGR);
    std::cout<<"imag empty "<<mat.empty()<<std::endl;
    cv::imwrite("test.jpg", mat);
    // cv::namedWindow("demo", cv::WINDOW_NORMAL);
    // cv::imshow("demo",mat);
    // cv::waitKey(0);
    // cv::destroyAllWindows();
    std::cout<<"done"<<std::endl;
    return 0;
}

image-20210125094230970

Visual studio Code 参考

Visual Code 预设路径:

${workspaceFolder} - the path of the folder opened in VS Code
${workspaceFolderBasename} - the name of the folder opened in VS Code without any slashes (/)
${file} - the current opened file
${relativeFile} - the current opened file relative to workspaceFolder
${relativeFileDirname} - the current opened file’s dirname relative to workspaceFolder
${fileBasename} - the current opened file’s basename
${fileBasenameNoExtension} - the current opened file’s basename with no file extension
${fileDirname} - the current opened file’s dirname
${fileExtname} - the current opened file’s extension
${cwd} - the task runner’s current working directory on startup
${lineNumber} - the current selected line number in the active file
${selectedText} - the current selected text in the active file
${execPath} - the path to the running VS Code executable

About: kiah


83 thoughts on “Windows 上使用Visual Studio Code”

  1. Fashions come and go, but it does seem there is a rising undercurrent of ‘grrr too complicated, and I’m not going to take this anymore!’. Rails is special for what it doesn’t try to do, rather than what it does – and that’s probably the meta-lesson. As for Alpha Geeks, quick pop quiz: Name three Microsoft-centric alpha geeks that don’t currently work at the big house? And there’s your answer. The career path for those on the Microsoft track is to end up at the Redmond mothership eventually, and there’s the rub: they gain the brains but lose the community. Long-tail and all that. Stay away from the light Scott Obi-Wan, you’re our only hope! 😉 PS I coughed flakes all over my laptop over your comment: ‘@James Avery – it’s about getting rails into the Enterprise. Hosting on Java or Windows is often more comfortable and understood than introducing Rails and Mongrel. ‘ – that doesn’t sound a compelling long-term strategy to learn something(RE:WS-*, SOA and anything else not clearly understood, i.e. image is key).

  2. Холостячка 2 сезон https://bit.ly/39ioLkW Смотреть онлайн шоу Холостячка 2 сезон на СТБ.
    Пост шоу можно смотреть тут. Холостячка стб 2 сезон 1-2 серия

  3. Холостячка 2 сезон https://bit.ly/39ioLkW Смотреть онлайн шоу Холостячка 2 сезон на СТБ.
    Пост шоу можно смотреть тут. Холостячка стб 2 сезон 1-2 серия

  4. Холостячка 2 сезон https://bit.ly/39ioLkW Смотреть онлайн шоу Холостячка 2 сезон на СТБ.
    Пост шоу можно смотреть тут. Холостячка стб 2 сезон 1-2 серия

  5. Холостячка 2 сезон https://bit.ly/39ioLkW Смотреть онлайн шоу Холостячка 2 сезон на СТБ.
    Пост шоу можно смотреть тут. Холостячка стб 2 сезон 1-2 серия

  6. Холостячка 2 сезон https://bit.ly/39ioLkW Смотреть онлайн шоу Холостячка 2 сезон на СТБ.
    Пост шоу можно смотреть тут. Холостячка стб 2 сезон 1-2 серия

  7. Консультация психолога онлайн. Консультация по Skype Индивидуальный подход к консультированию!
    Цены на услуги и консультации психолога.
    Профессиональные психологи. Онлайн-консультация у психолога.
    Консультация психолога. Індивідуальні консультації.

  8. Бій Усик — Джошуа. Український боксер Олександр Усик вийде на ринг проти британського чемпіона Ентоні Джошуа, офіційно бій за володіння титулом WBO вже призначили на 25 вересня. Згаданий бій Энтони Джошуа Александр Усик 2021.25.09 Олександр Усик і Ентоні Джошуа взяли участь у відкритому тренуванні напередодні чемпіонського поєдинку в надважкій вазі, який відбудеться 25 вересня у Лондоні, у Мережі з’явилися фото та відео з офіційного заходу

  9. Системные-расстановки.
    Расстановки Системно-феноменологический подход.
    Новые семейные расстановки. Bert Hellinger.
    Системно-феноменологический подход.

    Системные расстановки.

发表评论

电子邮件地址不会被公开。