一、cmake简介
cmake 是gnu工具链中构建项目重要的一环,而且在windows、linux、OS X中都可以使用,特别是linux C/C++程序员必备基本功。
二、基本命令:
命名变量:
SET(INC_DIR /usr/local/include)
SET(LINK_DIR /usr/local/lib)
SET(SOURCE_FILES main.cpp)
包含目录:相当于 -I
include_directories(${INC_DIR})
链接库目录:相当于 -L
link_directoried(${LINK_DIR})
引用库:需要放在 ADD_EXECUTABLE 后
target_link_libraries(target pthread cjson)
生成目标:
ADD_EXECUTABLE(main ${SOURCE_FILES})
三、例子:
使用cjson第三方库,cjson 已编译在 /usr/local/cjson 目录下。
1.示例代码:
#include <stdio.h>
#include <unistd.h>
#include "cjson/cJSON.h"
char *create_monitor(void)
{
const unsigned int resolution_numbers[3][2] = {
{1280, 720},
{1920, 1080},
{3840, 2160}
};
char *string = NULL;
cJSON *name = NULL;
cJSON *resolutions = NULL;
cJSON *resolution = NULL;
cJSON *width = NULL;
cJSON *height = NULL;
size_t index = 0;
cJSON *monitor = cJSON_CreateObject();
if (monitor == NULL)
{
goto end;
}
name = cJSON_CreateString("Awesome 4K");
if (name == NULL)
{
goto end;
}
/* after creation was successful, immediately add it to the monitor,
* thereby transferring ownership of the pointer to it */
cJSON_AddItemToObject(monitor, "name", name);
resolutions = cJSON_CreateArray();
if (resolutions == NULL)
{
goto end;
}
cJSON_AddItemToObject(monitor, "resolutions", resolutions);
for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index)
{
resolution = cJSON_CreateObject();
if (resolution == NULL)
{
goto end;
}
cJSON_AddItemToArray(resolutions, resolution);
width = cJSON_CreateNumber(resolution_numbers[index][0]);
if (width == NULL)
{
goto end;
}
cJSON_AddItemToObject(resolution, "width", width);
height = cJSON_CreateNumber(resolution_numbers[index][1]);
if (height == NULL)
{
goto end;
}
cJSON_AddItemToObject(resolution, "height", height);
}
string = cJSON_Print(monitor);
if (string == NULL)
{
fprintf(stderr, "Failed to print monitor.\n");
}
end:
cJSON_Delete(monitor);
return string;
}
int main(){
char* str = create_monitor();
if ( str != NULL ){
printf("%s\n",str);
}
return 0;
}
2.CMakeLists.txt文件内容:
PROJECT (test)
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
set(INC_DIR /usr/local/cjson/include)
set(LINK_DIR /usr/local/cjson/lib)
include_directories(${INC_DIR})
link_directories(${LINK_DIR})
ADD_EXECUTABLE(main main.c)
target_link_libraries(main cjson)
3.编译运行
mkdir build && cd build && cmake .. && make
./main