菜鸟笔记
提升您的技术认知

CMake install方法

阅读 : 1881

目录结构

├── cmake-examples.conf
├── CMakeLists.txt
├── include
│ └── Hello.h
└── src
├── Hello.c
└── main.c

源文件

main.c

#include "Hello.h"

int main(int argc, char *argv[])
{
  
    Hello_print();
    return 0;
}

Hello.c

#include "Hello.h"

void Hello_print(void)
{
  
    printf("install hello: cmake\r\n");
}

头文件

Hello.h

#ifndef __HELLO_H__
#define __HELLO_H__
#include <stdio.h>

void Hello_print(void);

#endif

CMakeLists.txt

cmake_minimum_required(VERSION 3.5)

project(cmake_examples_install)

############################################################
# Create a library
############################################################

#Generate the shared library from the library sources
add_library(cmake_examples_inst SHARED
    src/Hello.c
)

target_include_directories(cmake_examples_inst
    PUBLIC 
        ${
  PROJECT_SOURCE_DIR}/include
)

############################################################
# Create an executable
############################################################

# Add an executable with the above sources
add_executable(cmake_examples_inst_bin
    src/main.c
)

# link the new hello_library target with the hello_binary target
target_link_libraries( cmake_examples_inst_bin
    PRIVATE 
        cmake_examples_inst
)

############################################################
# Install
############################################################

# Binaries
install(TARGETS cmake_examples_inst_bin
    DESTINATION bin)

# Library
# Note: may not work on windows
install(TARGETS cmake_examples_inst
    LIBRARY DESTINATION lib)

# Header files
install(DIRECTORY ${
  PROJECT_SOURCE_DIR}/include/ 
    DESTINATION include)

# Config
install(FILES cmake-examples.conf
    DESTINATION etc)

)

编译

	$  mkdir build
	$  cd build/
	$  cmake ..
	$  make
	$  make install

测试

	$  ./hello_cmake
	install hello: cmake
	
	$ cat install_manifest.txt
	/usr/local/bin/cmake_examples_inst_bin
	/usr/local/lib/libcmake_examples_inst.so
	/usr/local/etc/cmake-examples.conf
	
	$  ls /usr/local/bin/
	cmake_examples_inst_bin
	$ ls /usr/local/lib
	libcmake_examples_inst.so
	$ ls /usr/local/etc/
	cmake-examples.conf
	$ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib cmake_examples_inst_bin
	install hello: cmake

说明

这样install的目录为 /usr/local 如果想改变install的目录有三种方式。
方式1:
在CMakeLists.txt 加入

set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install" CACHE STRING "The path to use for make install" FORCE)

方式2:
在cmake构建工程的时候加入参数

cmake -DCMAKE_INSTALL_PREFIX=./install ..

./install可以是任何目录,别忘了最后的两个点。

方式3:
.make install 时指定安装路径

make DESTDIR=./install