Ответ 1
Строка add_library должна быть все, что вам нужно. См. Этот пример кода, который я только что написал, чтобы проверить его создание, а затем использовать его (на Ubuntu 16.04):
Structure.h:
int sum( int a, int b );
Structure.c:
int sum( int a, int b ) {
return a + b;
}
main.c:
#include <stdio.h>
#include "Structure.h"
int main() {
int a = 5;
int b = 8;
int c = sum( a, b );
printf( "sum of %d and %d is %d\n", a, b, c );
return 0;
}
CMakeLists.txt:
# CMake instructions to make the static lib
ADD_LIBRARY( MyStaticLib STATIC
Structure.c )
# CMake instructions to test using the static lib
SET( APP_EXE StaticTest )
ADD_EXECUTABLE( ${APP_EXE}
Main.c )
TARGET_LINK_LIBRARIES( ${APP_EXE}
MyStaticLib )
А вот вот результат его запуска:
[email protected]:~/code/cmake/static_lib$ ls
CMakeLists.txt Main.c Structure.c Structure.h
[email protected]:~/code/cmake/static_lib$ cmake .
-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/nick/code/cmake/static_lib
[email protected]:~/code/cmake/static_lib$ ls
CMakeCache.txt CMakeFiles cmake_install.cmake CMakeLists.txt Main.c Makefile Structure.c Structure.h
[email protected]:~/code/cmake/static_lib$ make
Scanning dependencies of target MyStaticLib
[ 25%] Building C object CMakeFiles/MyStaticLib.dir/Structure.c.o
[ 50%] Linking C static library libMyStaticLib.a
[ 50%] Built target MyStaticLib
Scanning dependencies of target StaticTest
[ 75%] Building C object CMakeFiles/StaticTest.dir/Main.c.o
[100%] Linking C executable StaticTest
[100%] Built target StaticTest
[email protected]:~/code/cmake/static_lib$ ls
CMakeCache.txt cmake_install.cmake libMyStaticLib.a Makefile Structure.c
CMakeFiles CMakeLists.txt Main.c StaticTest Structure.h
[email protected]:~/code/cmake/static_lib$ ./StaticTest
sum of 5 and 8 is 13