cmake 各项目类型编译全记录

主要的例子

  1. 将一个不包含任何第三方库的源文件编译成可执行文件
  2. 将一个不包含任何第三方库的源文件编译成静态库
  3. 将一个包含第2步中静态库的源文件编译成可执行文件
  4. 将一个包含第2步中静态库的源文件编译成静态库
  5. 将一个包含第4步中静态库的源文件编译成可执行文件

1.将一个不包含任何第三方库的源文件编译成可执行文件

1.操作

新建一个CMakeLists.txt和main.cpp

2.项目组织架构

3.源文件

main.cpp

#include <stdio.h>
int main()
{	
	printf("hello world\n");	
	return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
add_executable(apple main.cpp)

4.执行

cmake .
make
./apple

5.结果

hello world

2.将一个不包含任何第三方库的源文件编译成静态库

1.操作

新建native.cpp,native.h,CMakeLists.txt

2.项目组织架构

3.源文件

native.cpp

#include "native.h"
void fun1()
{
	printf("im native fun1\n");
}

native.h

#include <stdio.h>
void fun1();

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
add_library(native STATIC native.cpp)

4.执行

cmake .
make

5.结果

生成了libnative.a


3.将一个包含第2步中静态库的源文件编译成可执行文件

1.操作

将第二步中生成的libnative.a和native.h拷贝到新的文件夹中

新建main.cpp和CMakeLists.txt

2.项目组织架构

3.源文件

main.cpp

#include "native.h"
int main()
{
	fun1();
	return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
link_directories(".")       #指定寻找库目录的路径,表示在当前文件夹下
add_executable(apple main.cpp)
target_link_libraries(apple native)

4.执行

cmake .
# warnning:出现警告,意思是我们在指定库目录路径时使用了相对路径,可能会出问题
# 暂时不管
make
./apple 

5.结果

im native fun1

4.将一个包含第2步中静态库的源文件编译成静态库

1.操作

将第二步中生成的libnative.a和native.h拷贝到新的文件夹中

新建new.cpp,new.h,CMakeLists.txt

2.项目组织架构

3.源文件

new.cpp

#include "native.h"
void fun2()
{
	printf("im new fun2\n");
	fun1();
}

new.h

#include <stdio.h>
void fun2();

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
add_library(new STATIC new.cpp)
add_library(native STATIC IMPORTED)
set_target_properties(native PROPERTIES IMPORTED_LOCATION libnative.a)
target_link_libraries(new native)

4.执行

cmake .
make

5.结果

生成了libnew.a

6.注意

libnew.a其中是不包含完整的libnative.a的,也就是libnew.a对libnative.a也只是一个调用关系。当我们想要使用libnew.a时,必须把libnative.a也包含进来。具体的例子在下面的第5块中。如果不包含libnative.a则会报错:对libnew.a中调用libnative.a的部分,未定义的引用。


5.将一个包含第4步中静态库的源文件编译成可执行文件

1.操作

将前面的libnative.a,native.h,libnew.a,new.h拷贝到新的文件夹中

新建main.cpp,CMakeLists.txt

2.项目组织架构

3.源文件

main.cpp

#include "new.h"
int main()
{
	fun2();
	return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
link_directories(".")
add_executable(apple main.cpp)
target_link_libraries(apple new native)

4.执行

cmake .
make
./apple

5.结果

im new fun2
im native fun1

本人还在找如何将两个静态库合并成一个静态库的方法,如果只用gcc命令行的ar可以直接实现,但是想要在cmake中实现还不行。如果可以实现,就可以把多个库进行打包,而不用将多个库都发布。

猜你喜欢

转载自blog.csdn.net/qq_34759481/article/details/84023233
今日推荐