CMake构建C#工程(protobuf)
工程目录结构
第一级CMakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
# 指定为csharp工程
project(CSharpDemo CSharp)
# 添加二级目录
add_subdirectory(src)
第二级CMakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
project(CSharpDemo CSharp)
# 指定protoc程序目录,用于执行输出cs文件
set(PROTOC_PATH ${CMAKE_SOURCE_DIR}/src/protoc)
add_subdirectory(BaseModel)
第三级CMakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
project(CSharpDemo CSharp)
# 指定编译器
set(CMAKE_CSharp_COMPILER "csc")
# 指定输出目录
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_SOURCE_DIR}/output/Debug)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_SOURCE_DIR}/output/Release)
set(cur_path ${CMAKE_CURRENT_SOURCE_DIR})
set(out_path ${CMAKE_CURRENT_BINARY_DIR})
message("*** ${PROTOC_PATH} ${cur_path} ${out_path}")
# 获取proto文件,proto文件首字母大写
file(GLOB proto_files *.proto)
# 遍历输出对应的cs文件
foreach(proto_file ${proto_files})
get_filename_component(proto_name ${proto_file} NAME_WE)
message("*** ${proto_file} ${proto_name}")
set(csharp_file "${proto_name}.cs")
add_custom_command(
OUTPUT ${csharp_file}
COMMAND protoc --csharp_out=${out_path} --proto_path=${cur_path} ${proto_name}.proto
WORKING_DIRECTORY ${PROTOC_PATH}
VERBATIM
)
list(APPEND csharp_files ${csharp_file})
endforeach()
add_executable(${PROJECT_NAME}
app.config
Program.cs TSimObject.cs
${csharp_files}
)
# 设置目标框架,与app.config中对应
set_property(TARGET ${PROJECT_NAME} PROPERTY VS_DOTNET_TARGET_FRAMEWORK_VERSION "v4.5")
# 设置引用第三方动态库
set_property(TARGET ${PROJECT_NAME} PROPERTY VS_DOTNET_REFERENCE_MyThirdPartyLib
../packages/Google.Protobuf.3.5.1/lib/net45/Google.Protobuf.dll
)
# 设置引用
set_property(TARGET ${PROJECT_NAME} PROPERTY VS_DOTNET_REFERENCES
"Google.Protobuf"
"Microsoft.CSharp"
"System"
"System.Core"
"System.Data"
"System.Data.DataSetExtensions"
)
通过build.bat执行编译
@echo off
cd /d %~dp0
mkdir build
cd build
cmake .. -G "Visual Studio 12 2013"
rem cmake --build . --config Debug
if "%1"=="" (cmake --build . --config Release) else (cmake --build . --config %1)
cd ..
pause
执行后的输出如下: