一、简单文件的编译
有如下的目录结构:
其中 helloworld.cpp如下:
#include <iostream>
using namespace std;
int main()
{printf("hello world my name is Ty!");return 0;
}
CMakeLists.txt如下:
cmake_minimum_required(VERSION 3.16.3)project(HELLOWORLD)add_executable(helloworld_cmake helloworld.cpp)
接下来新建一个build的文件夹
ty@ty-virtual-machine:~/桌面/code/5.5$ mkdir build
ty@ty-virtual-machine:~/桌面/code/5.5$ cd build
ty@ty-virtual-machine:~/桌面/code/5.5/build$ cmake …
…
ty@ty-virtual-machine:~/桌面/code/5.5/build$ make
运行结果:
二、多个文件夹的编译
有如下的目录
swap.h:
#pragma once
#include <iostream>
class swap
{
public:swap(int a,int b){m_a = a;m_b = b;}void run();void printInfo();
private:int m_a;int m_b;
};
swap.cpp:
#include "swap.h"
void swap::run()
{int ntemp;ntemp = m_a;m_a = m_b;m_b = ntemp;
}void swap::printInfo()
{printf("m_a = %d,m_b = %d\n",m_a,m_b);
}
main.cpp:
#include "swap.h"
int main(int argc, char **argv)
{swap swapth(10, 20);swapth.printInfo();swapth.run();swapth.printInfo();return 0;
}
其中CMakeLists.txt内容如下:
make_minimum_required(VERSION 3.16.3)
project(SWAPPRO)
include_directories(include)
add_executable(mymain_cmake main.cpp src/swap.cpp)
然后创建build文件夹:
mkdir build
然后进入:cd build
接着执行 cmake …
最后执行 make