protobuf cmakelist,msvc utf-8设置

源字符集和执行字符集
源字符集指的是cpp文件中字符串的编码方式
执行字符集指的是exe文件中字符串的编码方式

msvc编译器设置的命令行参数
/source-charset:utf-8 /execution-charset:utf-8

cmake中设置
add_compile_options(“ < < <:/source-charset:utf-8>”)

add_compile_options(“ < < <:/execution-charset:gbk>”)

# 必须在add_library , add_executable 前设置,否则无效
add_compile_options("$<$:/source-charset:utf-8>")

# protoc必须要加上这条!!!!!!!!!!!!!!!
add_definitions(-DPROTOBUF_USE_DLLS)

set(Protobuf_DIR "C:/Program Files/protobuf/lib/cmake/protobuf")
set(Absl_DIR "C:/Program Files/protobuf/lib/cmake/absl")
set(Utf8_DIR "C:/Program Files/protobuf/lib/cmake/utf8_range")

find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core Protobuf)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core)


# 设置 Protobuf 路径
set(PROTOC_PATH "C:/Program Files/protobuf/bin/protoc.exe")
# 查找 protoc 可执行文件
find_program(PROTOC_EXECUTABLE
    NAMES protoc
    PATHS ${PROTOC_PATH}
)
if(NOT PROTOC_EXECUTABLE)
    message(FATAL_ERROR "protoc not found. Please install it or set PROTOC_PATH.")
endif()
message(STATUS "Using protoc: ${PROTOC_EXECUTABLE}")

# 设置 proto 文件目录
set(PROTOBUF_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/proto")

# 设置生成文件输出目录
set(GENERATED_PROTO_DIR "${CMAKE_CURRENT_BINARY_DIR}/generated")

# 确保生成文件目录存在
file(MAKE_DIRECTORY ${GENERATED_PROTO_DIR})

# 设置 proto 文件列表
set(PROTO_FILES
    ${PROTOBUF_SRC_DIR}/addressbook.proto
)

# 为每个 proto 文件生成相应的 C++ 文件
foreach(PROTO_FILE ${PROTO_FILES})
    get_filename_component(PROTO_NAME ${PROTO_FILE} NAME_WE)
    set(GENERATED_SRC "${GENERATED_PROTO_DIR}/${PROTO_NAME}.pb.cc")
    set(GENERATED_HDR "${GENERATED_PROTO_DIR}/${PROTO_NAME}.pb.h")

    add_custom_command(
        OUTPUT ${GENERATED_SRC} ${GENERATED_HDR}
        COMMAND ${PROTOC_EXECUTABLE}
        ARGS --cpp_out=${GENERATED_PROTO_DIR} -I${PROTOBUF_SRC_DIR} ${PROTO_FILE}
        DEPENDS ${PROTO_FILE}
        COMMENT "Generating C++ source files from ${PROTO_FILE}"
        VERBATIM
    )

    list(APPEND GENERATED_SRC_FILES ${GENERATED_SRC})
endforeach()

# 将生成的 C++ 文件添加到构建目标中
add_executable(untitled1 main.cpp ${GENERATED_SRC_FILES})

# 添加生成文件目录到 include 路径
target_include_directories(untitled1 PRIVATE ${GENERATED_PROTO_DIR})

# 添加 Protobuf 头文件目录
target_include_directories(untitled1 PRIVATE "C:/Program Files/protobuf/include")

# 查找 C:\Program Files\protobuf\lib 下的所有 .lib 文件
file(GLOB PROTOBUF_LIBRARIES "C:/Program Files/protobuf/lib/*.lib")

# 打印找到的库文件(可选)
#message(STATUS "Protobuf libraries found: ${PROTOBUF_LIBRARIES}")
target_link_libraries(untitled1 Qt${QT_VERSION_MAJOR}::Core ${PROTOBUF_LIBRARIES})

你可能感兴趣的:(KBEngine,服务器)