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

運行結果如下圖:

感謝博主


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM