创建文件夹

mkdir my_proj

继续创建include 和 src文件夹,形成如下的目录结构

Ubuntu使用cmake和vscode开发自己的项目,引用自己的头文件和openCV-LMLPHP

用vscode打开项目

Ubuntu使用cmake和vscode开发自己的项目,引用自己的头文件和openCV-LMLPHP

创建add.h

#ifndef ADD_H
#define ADD_H
 
int add(int numA, int numB);
 
#endif

add.cpp

#include "add.h"
 
int add(int numA, int numB)
{
    return numA + numB;
}

main.cpp

#include <iostream>
#include "add.h"
 
int main()
{
   std::cout << "numA + numB = " << add(10,20) <<std::endl;
   return 0;
}

形成这样的目录结构

Ubuntu使用cmake和vscode开发自己的项目,引用自己的头文件和openCV-LMLPHP

在my_proj中创建CMakeLists.txt,写入如下内容

cmake_minimum_required(VERSION 2.8)

project(test)

set( CMAKE_BUILD_TYPE "Debug" )

include_directories(./include)

set(SRC_LIST ./src/add.cpp ./src/main.cpp)

add_executable(main ${SRC_LIST})

BUILD_TYPR 设置为Debug可以打断点调试

在my_proj中创建build.sh,写入如下内容

mkdir build
cd build
cmake ..
make

修改build.sh文件的权限

chmod +x build.sh

运行build.sh

Ubuntu使用cmake和vscode开发自己的项目,引用自己的头文件和openCV-LMLPHP

在build文件夹中,会生成一个main的可执行程序,将它的路径记下来

在vscode中ctrl+shift+d 创建一个launch.json,将刚才的main的可执行程序的路径复制到“program”:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "(gdb) Launch",
      "type": "cppdbg",
      "request": "launch",
      "program": "/home/robotics/my_proj/build/main",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${fileDirname}",
      "environment": [],
      "externalConsole": false,
      "MIMode": "gdb",
      "setupCommands": [
          {
              "description": "Enable pretty-printing for gdb",
              "text": "-enable-pretty-printing",
              "ignoreFailures": true
          },
          {
              "description": "Set Disassembly Flavor to Intel",
              "text": "-gdb-set disassembly-flavor intel",
              "ignoreFailures": true
          }
      ]
    }
  ]
}

c_cpp_properties.json这样写

{
    "configurations": [
        {
            "name": "linux-gcc-x64",
            "includePath": [
                "${workspaceFolder}/**",
                "${workspaceFolder}/include"
            ],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "${default}",
            "cppStandard": "${default}",
            "intelliSenseMode": "linux-gcc-x64",
            "compilerArgs": [
                ""
            ]
        }
    ],
    "version": 4
}

然后就可以打上断点调试了

如果想要引用openCV,CMakeLists.txt中这样写

find_package( OpenCV REQUIRED )
include_directories(./include
${OpenCV_INCLUDE_DIRS} 
)
target_link_libraries( main ${OpenCV_LIBS} )

vscode 中ctrl+shift+p创建task.json,写入如下内容

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "./build.sh",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

就可以在vscode中ctrl+shift+b 运行build.sh文件,不必在Terminal中运行了。

编译完成后按F5运行程序

10-06 02:17