Ubuntu under Cmake compiled C ++ program Helloworld

1, the preferred new construction directory

mkdir helloworld

2, the new file directory

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

The role of each folder:

After the implementation of the project directory command:

3, enter Src directory, create source files

cd src
touch main.cpp
touch helloworld.cpp

4, the return to parent directory, enter the include directory, create headers

cd ../include/
touch helloworld.h

5, the source and header files were written and saved

//  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

The results as shown below:

6, preparation of documents CMakeLists.txt

Project name and lowest version ①cmake

cmake_minimum_required(VERSION 2.8)
project(helloworld)

② Set compilation mode ( "debug" and "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

运行结果如下图:

感谢博主

Guess you like

Origin www.cnblogs.com/haijian/p/12039160.html
Recommended