当前位置: 代码迷 >> 综合 >> 3 cmake-生成dll和lib
  详细解决方案

3 cmake-生成dll和lib

热度:75   发布时间:2023-11-25 07:40:03.0

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;elsereturn 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_LISTCMakeLibDemo.cppCMakeLibDemo.hALU.hALU.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_LISTCMakeLibDemoUse.cppCMakeLibDemoUse.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;
}
  相关解决方案