1. An instance of static library and dynamic library construction (and uploaded to the system, the paths are: /usr/lib and /usr/unclude/hello)
1) Create a build folder (empty) and CMakeLists.txt in an empty project, the specific contents are as follows:
①CMakeLists.txt
PROJECT(HELLOLIB) ADD_SUBDIRECTORY(lib)
2) Build lib folder in empty project
3) Add hello.c, hello.h and CMakeLists.txt to the lib folder, the details are as follows:
①hello.c
#include "hello.h" void HelloFunc() { printf("Hello World\n"); }
②hello.h
#ifndef HELLO_H #define HELLO_H #include <stdio.h> void HelloFunc(); #endif
③CMakeLists.txt
SET(LIBHELLO_SRC hello.c) ADD_LIBRARY(hello SHARED ${LIBHELLO_SRC}) ADD_LIBRARY(hello_static STATIC ${LIBHELLO_SRC}) SET_TARGET_PROPERTIES(hello_static PROPERTIES OUTPUT_NAME "hello") GET_TARGET_PROPERTY(OUTPUT_VALUE hello_static OUTPUT_NAME) MESSAGE(STATUS "This is the hello_static OUTPUT_NAME:" ${OUTPUT_VALUE}) SET_TARGET_PROPERTIES(hello PROPERTIES CLEAN_DIRECT_OUTPUT 1) SET_TARGET_PROPERTIES(hello_static PROPERTIES CLEAN_DIRECT_OUTPUT 1) INSTALL(TARGETS hello hello_static LIBRARY DESTINATION lib ARCHIVE DESTINATION lib) INSTALL(FILES hello.h DESTINATION include/hello)
4) Enter the build path and enter in turn
①cmake -DCMAKE_INSTALL_PREFIX=/usr ..
②make
③make install
2. Use the library and header files uploaded by the installation
1) Create the src directory in the new project, write the source file main.c, and CMakeLists.txt
①main.c
#include <hello.h> intmain() { HelloFunc(); return 0; }
②CMakeLists.txt
INCLUDE_DIRECTORIES(/usr/include/hello)
TARGET_LINK_LIBRARIES(main hello)(或者TARGET_LINK_LIBRARIES(main libhello.so))
2) Create a build directory under the project, enter build on the command line to build
①cmake ..
②make
3. Special environment variables CMAKE_INCLUDE_PATH and CMAKE_LIBRARY_PATH
1) Why do you need these two environment variables: In order to use our own dynamic libraries and header files more intelligently
2) How to use? (used on top of our previous example)
①Enter export CMAKE_INCLUDE_PATH=/usr/include/hello in the command line
② Modify CMakeLists.txt in src to:
ADD_EXECUTABLE(main main.c) FIND_PATH(myHeader hello.h) IF(myHeader) INCLUDE_DIRECTORIES(${myHeader}) ENDIF(myHeader) TARGET_LINK_LIBRARIES(main libhello.so) LINK_DIRECTORIES(/home/wideking/cmakeDemo/libhello/bulid) ADD_EXECUTABLE(main main.c)
③ Build