一步步完成protobuf构建,并引入项目

RootPath:C:\Path\to

下载protobuf源码

下载CMake

CMake 构建 protobuf

搭建目录

image
DemoCMake: 将protobuf库和头文件引入的 Clion 项目
DemoVS: 将protobuf库和头文件引入的 VS 项目
install:编译后的protobuf安装目录
proto: 存放proto和编译生成文件的目录
protobuf: protobuf 源码

CMake Generate

1. 进入protobuf\cmake\build 分别新建debug, release, solution

2. 生成NMake debug版本项目结构

C:\Path\to\protobuf\cmake\build>mkdir debug & cd debug
   C:\Path\to\protobuf\cmake\build\release>cmake -G "NMake Makefiles" ^
    -DCMAKE_BUILD_TYPE=Debug ^
    -DCMAKE_INSTALL_PREFIX=../../../../install ^
    ../..

3. 生成NMake release版本项目结构

C:\Path\to\protobuf\cmake\build>mkdir release & cd release
   C:\Path\to\protobuf\cmake\build\release>cmake -G "NMake Makefiles" ^
    -DCMAKE_BUILD_TYPE=Release ^
    -DCMAKE_INSTALL_PREFIX=../../../../install ^
    ../..

4. 生成vs版本项目结构

C:\Path\to\protobuf\cmake\build>mkdir solution & cd solution
   C:\Path\to\protobuf\cmake\build\solution>cmake -G "Visual Studio 16 2019" ^
    -DCMAKE_INSTALL_PREFIX=../../../../install ^
    ../..

Build

NMake build

C:\Path\to\protobuf\cmake\build\debug>nmake

or

C:\Path\to\protobuf\cmake\build\release>nmake

VS Build

C:\Path\to\protobuf\cmake\build\debug>cmake --build .

or

C:\Path\to\protobuf\cmake\build\release>cmake --build .

Install

NMake Install

C:\Path\to\protobuf\cmake\build\release>nmake install
or
C:\Path\to\protobuf\cmake\build\debug>nmake install

将在install目录下安装编译后的文件

  • bin - that contains protobuf protoc.exe compiler;
  • include - that contains C++ headers and protobuf *.proto files;
  • lib - that contains linking libraries and CMake configuration files for protobuf package.

引入项目步骤

设置头文件目录

cmake: include_directories(../install/include)
vs: add include
add-include

设置lib目录

cmake: link_directories(../install/lib)
vs:add lib
add-lib

将制定目录下的文件附给变量

cmake: aux_source_directory(. DIR_SRC)
vs: 无

设置执行的文件

cmake: add_executable(DemoCMake ${DIR_SRC})
vs: 无

设置链接库

cmake: target_link_libraries(DemoCMake libprotobufd libprotocd)
vs:add output

  • debug使用的是libprotobufd.lib,libprotocd.lib
  • release使用的是 libprotobuf.lib,libprotoc.lib
    add-output

将VS的RuntimeLibrary 设置为MTD

cmake: set_property(TARGET DemoCMake PROPERTY MSVC_RUNTIME_LIBRARY “MultiThreaded$<$CONFIG:Debug:Debug>”)
vs:add RuntimeLibray

  • debug使用的是/MTd
  • release使用的是 /MT
    add-RuntimeLibray

CMakeLists.txt

# 设置头文件目录
include_directories(../install/include)

# 设置lib目录
link_directories(../install/lib)

#将制定目录下的文件附给变量
aux_source_directory(. DIR_SRC)

#设置执行的文件
add_executable(DemoCMake ${DIR_SRC})

#设置链接库
target_link_libraries(DemoCMake libprotobufd libprotocd)

#将VS的RuntimeLibrary 设置为MTD
set_property(TARGET DemoCMake PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")

来源:目录protobuf\cmake\README.md