3 cmake-生成dll和lib

1 cmake 版本库
2 cmake 添加库
1 工程目录
在这里插入图片描述

最顶层的CMakeList.txt添加

add_subdirectory (CMakeLibDemo)
add_subdirectory (CMakeLibDemoUse)

2 文件
ALU.h

#pragma once
#define DllExport   __declspec( dllexport )//宏定义
#ifndef ALU_H 
#define ALU_H 
#include <iostream> 
using namespace std;
class DllExport ALU //要生成dll必须加上这个宏,否则会出错
{
public:
	ALU(int opr_a, int opr_b)
	{
		a = opr_a;
		b = opr_b;
	};
	~ALU() {};
	int add();
	int sub();
	int mul();
	int div();
private:
	int a;
	int b;
};

#endif 

ALU.cpp

#include "ALU.h"

int ALU::add()
{
	return a + b;
}

int ALU::sub()
{
	return a - b;
}

int ALU::mul()
{
	return a * b;
}

int ALU::div()
{
	if (b != 0)
		return a / b;
	else
		return 0;
}

CMakeLibDemo/CMakeLibDemo.cpp

#include "CMakeLibDemo.h"
#include "ALU.h"
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main()
{
	ALU alu1(4, 2);
	int get_add, get_sub, get_mul, get_div;
	get_add = alu1.add();
	get_sub = alu1.sub();
	get_mul = alu1.mul();
	get_div = alu1.div();
	cout << get_add << endl;
	cout << get_sub << endl;
	cout << get_mul << endl;
	cout << get_div << endl;
	system("Pause");
	return 0;
}

CMakeLibDemo/CMakeList.txt

project ("CMakeLibDemo")
cmake_minimum_required (VERSION 3.8)

set ( SRC_LIST
	CMakeLibDemo.cpp
	CMakeLibDemo.h
	ALU.h
	ALU.cpp
)

添加库

add_library(ALU SHARED ALU.cpp) #想得到动态库,参数就是SHARED

将源代码添加到此项目的可执行文件

add_executable(CMakeLibDemo ${SRC_LIST})

将库链接到程序

target_link_libraries(CMakeLibDemo ALU)

3 运行
选择执行项目
在这里插入图片描述

生成库
在这里插入图片描述

生成的库:C:\Users\zhumengbo\CMakeBuilds\f5b388cb-20d5-a535-8801-6fc8347ad0fd\build\x64-Debug (默认值)\CMakeLibDemo

4 使用生成的库
4.1 工程目录
把生成的dll和lib,放在deps/ALU中
在这里插入图片描述

4.2 CMakeLibDemoUse/CMakeList.txt

project ("CMakeLibDemoUse")
cmake_minimum_required (VERSION 3.8)

set ( SRC_LIST
	CMakeLibDemoUse.cpp
	CMakeLibDemoUse.h
)

添加头文件目录

include_directories (CMakeLibDemoUse
	${ALU_INCLUDE_DIR}
)
#添加库目录
link_directories (
	${ALU_LIBARY}
)

add_executable(CMakeLibDemoUse ${SRC_LIST})

将库链接到程序

target_link_libraries (CMakeLibDemoUse ALU)

CMakeLibDemoUse/CMakeLibDemoUse.cpp
#include "CMakeLibDemo.h"
#include "ALU.h"
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main()
{
	ALU alu1(4, 2);
	int get_add, get_sub, get_mul, get_div;
	get_add = alu1.add();
	get_sub = alu1.sub();
	get_mul = alu1.mul();
	get_div = alu1.div();
	cout << get_add << endl;
	cout << get_sub << endl;
	cout << get_mul << endl;
	cout << get_div << endl;
	system("Pause");
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值