实例分享cmake编译一个简单c++项目(demo)

发布时间:2020-09-19 21:08:04 作者:mdxy-dxy
来源:脚本之家 阅读:231

下面通过一个小例子来说明cmake编译一个c++项目,生成可执行文件:

整理目录结构:

CMake Lists.txt addlib build main.cpp

电脑上没有tree命令,也不大敢截图,将就着看看,其中build是cmake编译指定的路径,addlib下面也有一个头文件和源文件  ,还有一个CmakeLists.txt,可以看下:

CMake Lists.txt library.cpp library.h

先看各个文件的代码:

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(accliblibrary)
 
set(CMAKE_CXX_STANDARD 11)
 
add_library(accliblibrary SHARED library.cpp library.h) # 诉生成一个库文件。

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(cppproject)
 
set(CMAKE_CXX_STANDARD 11)
 
add_subdirectory(acclib)
 
 
add_executable(cppproject main.cpp) #生成一个可执行的文件
 
target_link_libraries(cppproject accliblibrary)

下面就是编译该项目,生成可执行文件:

cd build/

cmake ..

-- The C compiler identification is AppleClang 8.0.0.8000042
-- The CXX compiler identification is AppleClang 8.0.0.8000042
-- Check for working C compiler: /Library/Developer/CommandLineTools/usr/bin/cc
-- Check for working C compiler: /Library/Developer/CommandLineTools/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: /Library/Developer/CommandLineTools/usr/bin/c++
-- Check for working CXX compiler: /Library/Developer/CommandLineTools/usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/zhoumeixu/Documents/cmakedemo/build

make:

Scanning dependencies of target addliblibrary
[ 25%] Building CXX object addlib/CMakeFiles/addliblibrary.dir/library.cpp.o
[ 50%] Linking CXX shared library libaddliblibrary.dylib
[ 50%] Built target addliblibrary
Scanning dependencies of target cmakedemo
[ 75%] Building CXX object CMakeFiles/cmakedemo.dir/main.cpp.o
[100%] Linking CXX executable cmakedemo
[100%] Built target cmakedemo

./cmakedemo

1+....+10=45

这篇文章就介绍下面,下面亿速云小编将继续为大家介绍

推荐阅读:
  1. GNU开发工具——CMake快速入门
  2. 三百行代码完成一个简单的rpc框架

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

cmake编译 c++ 项目

上一篇:Vue 实现CLI 3.0 + momentjs + lodash打包时优化

下一篇:Mysql 通过frm&ibd 恢复数据

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》