软件环境
Windows | 11 |
VS Code | None |
CMake | 3.26.4-windows-x86_64 |
MinGW | None |
电脑系统配置
- 安装MinGW
- 将MinGW安装文件夹中bin文件夹下的mingw32-make.exe复制并重命名为make.exe
- 在文件夹中添加系统路径,具体位置为 系统->系统信息->高级系统设置->高级->环境变量->系统变量->path 中确保以下路径已经被添加
如下所示:
CMake设置
在CMake中,设置以下变量(根据自己电脑配置进行更改)
set(CMAKE_GENERATOR "MinGW Makefiles")
set(CMAKE_MAKE_PROGRAM "D:/MinGW/bin/make.exe")
set(CMAKE_C_COMPILER "D:/MinGW/bin/gcc.exe")
set(CMAKE_CXX_COMPILER "D:/MinGW/bin/g++.exe")
编写简单代码,代码文件结构如下所示
—代码文件夹
——bin
——build
——include
———hello.hpp
———hello2.hpp
——lib
——src
———run.cpp
———hello.cpp
———hello2.cpp
——CMakeLists.txt
CMakeLists.txt文件内容如下
cmake_minimum_required(VERSION 3.0)
project(HELLO)
set(CMAKE_GENERATOR "MinGW Makefiles")
set(CMAKE_MAKE_PROGRAM "D:/MinGW/bin/make.exe")
set(CMAKE_C_COMPILER "D:/MinGW/bin/gcc.exe")
set(CMAKE_CXX_COMPILER "D:/MinGW/bin/g++.exe")
include_directories(
${PROJECT_SOURCE_DIR}/include
)
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
add_library(hello SHARED
${PROJECT_SOURCE_DIR}/src/hello.cpp
${PROJECT_SOURCE_DIR}/src/hello2.cpp
)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
add_executable(test ${PROJECT_SOURCE_DIR}/src/run.cpp)
target_link_libraries(test hello)
src/run.cpp内容如下
#include <iostream>
#include <stdio.h>
#include "hello.hpp"
int main(int argc, char** argv)
{
printf("hello\n");
printf("run:%s\n", argv[0]);
hello_inclode();
printf("enter any key to exit\n");
getchar();
exit(0);
}
src/hello.cpp内容如下
#include "hello.hpp"
#include "hello2.hpp"
void hello_inclode(void)
{
printf("include hello.cpp\n");
hello2_include();
}
src/hello2.cpp内容如下
#include "hello2.hpp"
void hello2_include(void)
{
printf("hello2 include\n");
}
include/hello.hpp内容如下
#ifndef __HELLO_H__
#define __HELLO_H__
#include <stdio.h>
void hello_inclode(void);
#endif
include/hello2.hpp内容如下
#ifndef __HELLO_H__
#define __HELLO_H__
#include <stdio.h>
void hello2_include(void);
#endif
在build文件夹中使用cmake指令进行编译,虽然在CMakeLists.txt中指定了生成器,但是在目前版本中生成的并不是该变量指定的参数,因此添加-G参数,具体指令如下:
cmake -G="MinGW Makefiles" ..
make
执行bin文件结果如下所示: