标签:CMake 入门 -- CXX 使用 cpp main hello compiler
在Linux系统下使用cmake工具构建项目的简单示例,内容来自《CMake Practice》。
1. 准备工作
新建文件夹t1,然后在t1文件夹下新建hello.h
,hello.cpp
,main.cpp
和CMakeLists.txt
(注意大小写)。
目录结构:
t1
|______hello.h
|______hello.cpp
|______main.cpp
|______CMakeLists.txt
文件内容:
hello.h
# ifndef HELLO_H
# define HELLO_H
void print();
# endif
hello.cpp
# include "hello.h"
# include <iostream>
void print() {
std::cout << "Hello world!" << std::endl;
}
main.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
return 0;
}
CMakeLists.txt
project(HELLO)
set(SRC_LIST main.cpp hello.h hello.cpp)
add_executable(hello ${SRC_LIST})
代码解释
-
project(HELLO)
,将项目名称设置为HELLO
-
set(SRC_LIST main.cpp)
,其中set
指令用来设置变量,将变量的值设置为后面的字符串,这里用SRC_LIST
代替main.cpp hello.h hello.cpp
-
add_executable(hello ${SRC_LIST})
,其中hello
是可执行文件的文件名,后面跟需要的源文件名,这里使用变量SRC_LIST
代替所有源文件,引用变量时用${}
将变量括起来
2. 开始构建
t1目录中应该包含main.cpp
和CMakeLists.txt
这两个文件。将工作目录切换到t1,在目录中运行命令
cmake . # .代表当前工作目录
如果是在Windows系统下使用MinGW的话,需要指定生成的makefile的版本
cmake -G "MinMG Makefiles" . # Windows+MinGW
输出大概是这个样子
-- The C compiler identification is GNU 9.3.0
-- The CXX compiler identification is GNU 9.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- This is BINARY dir /home/xxx/Documents/cmake/t1
-- This is SOURCE dir /home/xxx/Documents/cmake/t1
-- Configuring done
-- Generating done
-- Build files have been written to: /home/xxx/Documents/cmake/t1
这个时候目录里自动生成了Makefile
文件,在当前文件夹下使用make
命令构建
make
会看到以下输出
Scanning dependencies of target hello
[ 50%] Building CXX object CMakeFiles/hello.dir/main.cpp.o
[100%] Linking CXX executable hello
[100%] Built target hello
这时候会发现目录里生成了目标文件hello
,用以下命令执行目标文件,
./hello
得到输出Hello world!
标签:CMake,入门,--,CXX,使用,cpp,main,hello,compiler 来源: https://www.cnblogs.com/lzqttkx/p/15115763.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。