cmake的使用總結

Linux袁浩發表於2024-03-22

cmake的使用總結

參考連結

https://subingwen.cn/cmake/CMake-primer/
https://subingwen.cn/cmake/CMake-advanced/?highlight=cmake

CMake檔案

yh@ubuntu:/Test/jsoncpp$ tree
.
├── build
├── CMakeLists.txt
├── json
│   ├── allocator.h
│   ├── assertions.h
│   ├── config.h
│   ├── forwards.h
│   ├── json_features.h
│   ├── json.h
│   ├── reader.h
│   ├── value.h
│   ├── version.h
│   └── writer.h
├── main.cpp
└── src
    ├── json_reader.cpp
    ├── json_tool.h
    ├── json_value.cpp
    ├── json_valueiterator.inl
    └── json_writer.cpp

3 directories, 17 files

CMakeLists.txt檔案

cmake_minimum_required(VERSION 3.5)

project(jsoncpp)
include_directories(${PROJECT_SOURCE_DIR})
file(GLOB LIBRARY_SRC_LIST "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")

#設定靜態庫和動態庫所需的中間檔案列表
set(LIBRARY_OBJS_LIST ${PROJECT_NAME}-objs)
add_library(${LIBRARY_OBJS_LIST} OBJECT ${LIBRARY_SRC_LIST})
#開啟靜態庫和動態庫所需的中間檔案的PIC編譯選項
set_target_properties(${LIBRARY_OBJS_LIST} PROPERTIES POSITION_INDEPENDENT_CODE True)

#生成jsoncpp靜態庫
#設定靜態庫檔案臨時名稱
set(TMP_STATIC_LIB_NAME ${PROJECT_NAME}-static)
#生成靜態庫檔案
add_library(${TMP_STATIC_LIB_NAME} STATIC $<TARGET_OBJECTS:${LIBRARY_OBJS_LIST}>)
#設定靜態庫檔案的最終名稱
set_target_properties(${TMP_STATIC_LIB_NAME} PROPERTIES OUTPUT_NAME ${PROJECT_NAME})

#生成jsoncpp動態庫
#設定動態庫檔案臨時名稱
set(TMP_SHARED_LIB_NAME ${PROJECT_NAME}-shared)
#生成動態庫檔案
add_library(${TMP_SHARED_LIB_NAME} SHARED $<TARGET_OBJECTS:${LIBRARY_OBJS_LIST}>)
#設定動態庫檔案的最終名稱
set_target_properties(${TMP_SHARED_LIB_NAME} PROPERTIES OUTPUT_NAME ${PROJECT_NAME})

#生成測試檔案
add_executable(testjsoncpp main.cpp)
target_link_libraries(testjsoncpp ${TMP_STATIC_LIB_NAME})

main.cpp

#include <json/json.h>
#include <iostream>

using namespace std;

int main(int argc, const char *argv[])
{
	Json::Value root;
	Json::FastWriter writer;
	Json::StreamWriterBuilder wBuilder;
	root["name"] = "張三";
	root["age"] = 18;
	cerr << writer.write(root) << endl;
	std::cout << Json::writeString(wBuilder, root) << std::endl;
	return 0;
}

修復jsoncpp1.9.5中的中文被顯示為\u的錯誤

json_writer.cpp第275行

static String valueToQuotedStringN(const char* value, size_t length,
                                   bool emitUTF8 = false)
修改為
static String valueToQuotedStringN(const char* value, size_t length,
                                   bool emitUTF8 = true)

json_writer.cpp第1239行

(*settings)["emitUTF8"] = false;
修改為
(*settings)["emitUTF8"] = true;

Linux下編譯步驟

進入build目錄開始編譯
cd build && cmake .. && make -j8

windows下編譯

方式1

cd build
cmake -G "NMake Makefiles" ..
nmake

方式2

#參考https://developer.valvesoftware.com/wiki/Building_without_Visual_Studio#Step_2:_Compiling
cd build
cmake ..
msbuild jsoncpp.sln