zoukankan      html  css  js  c++  java
  • Ubuntu下Cmake编译C++程序Helloworld

    1、首选新建工程目录

    mkdir helloworld

    2、新建文件目录

    cd helloworld
    mkdir bin
    mkdir lib
    mkdir src
    mkdir include
    mkdir build
    touch CMakeLists.txt

    各文件夹的作用:

    执行命令之后的工程目录:

    3、进入Src目录,新建源文件

    cd src
    touch main.cpp
    touch helloworld.cpp
    

    4、返回上级目录,进入include目录,新建头文件

    cd ../include/
    touch helloworld.h
    

    5、对源文件和头文件进行编写并保存

    //  main.cpp
    #include <helloworld.h>
    int main()
    {
    	helloworld obt;
    	obt.outputWord();
    	return 0;
    }
    
    //  helloworld.cpp
    #include "helloworld.h"
    void helloworld::outputWord()
    {
    	std::cout << "hello world!" << std::endl;
    }
    
    //  helloworld.h
    #ifndef HELLOWORLD_H_
    #define HELLOWORLD_H_
    #include <iostream>
    class helloworld
    {
    public:
    	void outputWord();
    };
    #endif

    结果如下图:

    6、编写CMakeLists.txt文件

    ①cmake最低版本以及工程名称

    cmake_minimum_required(VERSION 2.8)
    project(helloworld)

    ②设置编译方式(“debug”与“Release“)

    SET(CMAKE_BUILD_TYPE Release)
    

    ③设置可执行文件与链接库保存的路径

    set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
    set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
    

    ④设置头文件目录使得系统可以找到对应的头文件

    include_directories(
    ${PROJECT_SOURCE_DIR}/include
    )
    

    ⑤选择需要编译的源文件,凡是要编译的源文件都需要列举出来

    add_executable(helloworld src/helloworld.cpp src/main.cpp)
    

    结果如下图:

    7、编译程序

    cd build
    cmake ..
    make
    

    8、查看编译结果

    9、运行程序

    ./../bin/helloworld
    

    运行结果如下图:

    感谢博主

  • 相关阅读:
    Dapper笔记-Dapper.Common【转】
    ASP.Net Core WebApi几种版本控制对比【转】
    ASP.NET Core WebAPI使用Swagger生成文档
    K8S笔记-Pod介绍【未完成】
    Docker-容器命令
    MySQL笔记-备份命令(mysqldump)
    MySQL笔记-INFORMATION_SCHEMA数据库介绍【转】
    Quartz.net笔记-计划任务触发器(Cron Trigger)
    Quartz.net笔记-简单触发器(Simple Trigger)
    Type序列化器
  • 原文地址:https://www.cnblogs.com/haijian/p/12039160.html
Copyright © 2011-2022 走看看