Qt添加CMake支持
1、下载CMake并解压
参考https://cmake.org/download/
$ wget https://cmake.org/files/v3.12/cmake-3.12.0-rc3.tar.gz
$ tar xvf cmake-3.12.0-rc3.tar.gz
2、编译并安装CMake
$ cd cmake-3.12.0-rc3/
$ ./bootstrap
$ make -j8
$ sudo make install
3、配置Qt
Qt-->Tools-->Options-->Build & Run-->CMake-->Add
Name:随意,姑且取cmake-3.12.0-rc3
Path:/home/yong/Downloads/cmake-3.12.0-rc3/bin/cmake,即编译出来的CMake命令的绝对路径。
Qt->Tools->Options->Build & Run->Kits->Desktop(dafault)->CMake Tool
创建CMake项目
New Project-->Non-Qt Project-->Plain C++ Application-->...
在选择Build System时,选择CMake
在Kit Selection时选择上面配置的Desktop(dafault)
项目描述如下文件CMakeLists.txt如下:
cmake_minimum_required(VERSION 2.8)
project(cmake-test)
add_library( # Sets the name of the library.
test_hello
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
./hello.cpp
)
add_executable(${PROJECT_NAME} "main.cpp")
target_link_libraries( # Specifies the target library.
cmake-test
test_hello)
这个文件解释如下:
cmake版本>2.8
项目名称是cmake-test
有两个模块:动态链接库模块test_hello,可执行模块${PROJECT_NAME}=cmake-test
其中cmake-test模块需要动态链接test_hello库
main.cpp如下:
#include <iostream>
#include"hello.h"
#include <stdlib.h>
using namespace std;
int main()
{
char* result=sayHello("yong");
cout<<result<<endl;
free(result);
return 0;
}
hellp.cpp如下:
#include"hello.h"
#include<iostream>
#include <stdlib.h>
#include<string.h>
using namespace std;
char* sayHello(const char* name){
string cpp_name=name;
string result=cpp_name+"-->hello";
char* c_result=(char*)malloc((result.length()+1)*sizeof(char));
memcpy(c_result,(const char*)&result[0],result.length()+1);
return c_result;
}
hello.h如下:
#ifndef HELLO_H
#define HELLO_H
char* sayHello(const char* name);
#endif // HELLO_H
编译项目,运行
1、可以手动编译,例如项目地址是cmake-test
$ tree cmake-test/
cmake-test/
├── CMakeLists.txt
├── CMakeLists.txt.user
├── hello.cpp
├── hello.h
└── main.cpp
0 directories, 5 files
$ cd cmake-test/
$ mkdir build
$ cd build/
$ cmake ..
$ make
Scanning dependencies of target test_hello
[ 25%] Building CXX object CMakeFiles/test_hello.dir/hello.cpp.o
[ 50%] Linking CXX shared library libtest_hello.so
[ 50%] Built target test_hello
Scanning dependencies of target cmake-test
[ 75%] Building CXX object CMakeFiles/cmake-test.dir/main.cpp.o
[100%] Linking CXX executable cmake-test
[100%] Built target cmake-test
$ ls
CMakeCache.txt cmake_install.cmake libtest_hello.so
CMakeFiles cmake-test Makefile
在cmake-test/build下的cmake-test可执行文件和libtest_hello.so就是我们想要的东西。