前提准备:是手动安装好了gcc编译器
gcc编译器的安装
https://www.jianshu.com/p/1e1276e05f3f
1.首先整体的目录结构
[root@iZuf6ac930m7q6b48s3u34Z cmakedemo]# tree .
|-- CMakeLists.txt
|-- addlib
| |-- CMakeLists.txt
| |-- library.cpp
| `-- library.h
|-- build
| `-- main.cpp
先看各个文件的代码:
addlib/library.h:
#ifndef CPPPROJECT_LIBRARY_H
#define CPPPROJECT_LIBRARY_H
int acc_add(int);
#endif
addlib/library.cpp:
#include "library.h"
#include <iostream>
void hello(){
std::cout<<"hello world"<<std::endl;
}
int acc_add(int n){
int sum=0;
for(int i=0;i<n;i++){
sum+=i;
}
return sum;
}
addlib/CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
project(addlib)
set(CMAKE_CXX_STANDARD 11)
add_library(addlib SHARED library.cpp library.h) # create a dynamic library file
main.cpp:
#include <iostream>
#include <string>
#include "addlib/library.h"
using namespace std;
int main(){
int n=10;
int ans=acc_add(n);
cout<<"1+....+"<<n<<"="<<ans<<endl;
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(accliblibrary) #define a projectname
set(CMAKER_CXX_STANDARD 11) # show the variable
add_subdirectory(addlib output) # add sub directory of source code and define the directory where the binary code is put
add_executable(cppproject main.cpp) #create an executable file cppproject
target_link_libraries(cppproject addlib) # 向target添加需要链接的共享库
下面就是编译该项目,生成可执行文件:
cd build/
cmake ..
make
./cppproject
1+....+10=45