此文章基于Windows 和CLion介绍
示例:
创建C语言项目
使用CLoin 新建项目,如下图:
例如项目名为 MyCLibrary
library.h
1 2 3 4 5 6 7
| #ifndef MYCLIBRARY_LIBRARY_H #define MYCLIBRARY_LIBRARY_H
void hello_from_c(void);
#endif
|
library.c
1 2 3 4 5 6
| #include <stdio.h> #include "library.h" void hello_from_c() { printf("Hello from C!\n"); }
|
CMakeLists.txt
1 2 3 4 5 6 7 8 9 10 11 12 13
| cmake_minimum_required(VERSION 3.19) project(MyCLibrary C)
set(CMAKE_C_STANDARD 99)
add_library(MyCLibrary SHARED library.c library.h)
# 设置输出名称为MyCLibrary.dll,不带lib前缀 set_target_properties(MyCLibrary PROPERTIES PREFIX "")
# 暴露头文件路径 target_include_directories(MyCLibrary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
构建项目,会在项目的 cmake-build-debug 文件夹下生成一个 MyCLibrary.dll 文件
创建C++项目
使用CLoin 新建项目,如下图:
例如项目名为 MyCppProject
将生成的 MyCLibrary.dll 文件放在主目录下
main.cpp
1 2 3 4 5 6 7 8
| extern "C" void hello_from_c();
int main() hello_from_c(); return 0; }
|
CMakeLists.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| cmake_minimum_required(VERSION 3.19) project(MyCppProject)
add_library(MyCLibrary SHARED IMPORTED) set_target_properties(MyCLibrary PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/MyCLibrary.dll) set_target_properties(MyCLibrary PROPERTIES IMPORTED_IMPLIB ${CMAKE_CURRENT_SOURCE_DIR}/MyCLibrary.dll)
set(CMAKE_CXX_STANDARD 14)
add_executable(MyCppProject main.cpp)
target_link_libraries(MyCppProject PRIVATE MyCLibrary)
|
再将 MyCLibrary.dll 文件放在主目录下 MyCppProject\cmake-build-debug 目录下,不然在执行时会报错找不到 MyCLibrary.dll