Tutorial - use cmake to compile static library and then use this library
First job is to compile a static library stat.a
- Two source files are involved in this library: func1.c and func2.c
func1.c
void func1(int *i)
{
*i = 8;
}
func2.c
void func2(int *i)
{
*i = 10;
}
- Create a cmake file "CMakeLists.txt"
cmake_minimum_required(VERSION 2.8.12.2)
project(test) # project name
set(CMAKE_BUILD_TYPE Release)
include_directories("directory_to_include_files")
set(SOURCES "func1.c" "func2.c") # source files
add_library(ctest_cmake STATIC ${SOURCE}) # generate static library *.a
- Add folder "build", inside "build", run:
$ cmake ..
-- Configuring done
-- Generating done
-- Build files have been written to: /home_dir/static_lib_examples/build
$ make
[100%] Built target ctest_cmake
at this point, a static library libc_test_cmake.a is seen in "build" folder.
- Create a "run" folder, in this folder, add main function and include files.
#include <stdio.h>
#include "stat.h"
int main()
{
int output;
func1(&output);
printf("output1 is %d\n", output);
func2(&output);
printf("output2 is %d\n", output);
return 0;
}
and include file stat.h:
void func1(char *);
void func2(char *);
- Create another cmake file inside "run" folder, CMakeLists.txt
cmake_minimum_required(VERSION 2.8.12.2)
project(test)
set(PROJECT_LINK_LIBS libctest_cmake.a)
link_directories(/home_dir/static_lib_examples/build)
add_executable(test.exe test.c)
target_link_libraries(test.exe ${PROJECT_LINK_LIBS}) #link *.a to test.exe
- Next, run cmake and make:
$ cmake .
-- Configuring done
-- Generating done
-- Build files have been written to: /home_dir/static_lib_examples/run
$ make
[100%] Built target test.exe
At this point, executable file "test.exe" is generated.
$ ./test.exe
output1 is 8
output2 is 10
Summary:
- by using cmake, users do not need to write make files.
- Two cmake files are involved here, the first one is to compile a static library, and the second one is to use this static library.
1. Static, Shared Dynamic and Loadable Linux Libraries
2. Introduction to CMake by Example