Development

CMake - 2부 (라이브러리 추가)

chbae 2023. 4. 18. 06:03
728x90
반응형

이 글에서는 CMake - 1부를 이어 Step 2를 정리하도록 한다. 필자는 http://www.cmake.org/cmake-tutorial/ 의 내용을 정리하고 있다.

Step 2: 라이브러리 추가

컴파일러에서 제공하는 square를 사용하지 않고, 직접 구현한 library 내에 있는 square root of number를 사용한다. 사용하기 위해서 아래와 같이 CMakeLists 파일에 추가한다.

1:  add_library(MathFunctions mysqrt.cxx)

line 1에서 MathFunctions/mysqrt.h header를 사용하기 위해 include directory를 추가한다.

line 2에서 새로 구성할 library를 빌드/사용하기 위해 add_subdirectory를 최상위 CMakeLists 파일에 추가한다.

line 5에서는 신규 library를 Tutorial 실행파일 빌드하는데 linking을 한다.

1:  include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")  
2:  add_subdirectory (MathFunctions)   
3:  # add the executable  
4:  add_executable (Tutorial tutorial.cxx)  
5:  target_link_libraries (Tutorial MathFunctions)

MathFunctions 라이브러리 사용 옵션을 추가한다. 우선 line 2에서와 같이 최상위 CMakeLists 파일에 사용자 지정 옵션 변수인 USE_MYMATH를 추가한다. 아래 default 값은 ON이다.

1:  # should we use our own math functions?  
2:  option (USE_MYMATH   
3:      "Use tutorial provided math implementation" ON)

아래는 USE_MYMATH 설정에 따라 조건적으로 빌드를 할 수 있도록 line 3 ~ line 7, line 10을 추가/수정하였다.

1:  # add the MathFunctions library?  
2:  #  
3:  if (USE_MYMATH)  
4:   include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")  
5:   add_subdirectory (MathFunctions)  
6:   set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)  
7:  endif (USE_MYMATH)  
8:  # add the executable  
9:  add_executable (Tutorial tutorial.cxx)  
10:  target_link_libraries (Tutorial ${EXTRA_LIBS})

아래와 같이 소스코드에도 반영을 한다.

1:  // A simple program that computes the square root of a number  
2:  #include <stdio.h>  
3:  #include <stdlib.h>  
4:  #include <math.h>  
5:  #include "TutorialConfig.h"  
6:  #ifdef USE_MYMATH  
7:  #include "MathFunctions.h"  
8:  #endif  
9:  int main (int argc, char *argv[])  
10:  {  
11:   if (argc < 2)  
12:    {  
13:    fprintf(stdout,"%s Version %d.%d\n", argv[0],  
14:        Tutorial_VERSION_MAJOR,  
15:        Tutorial_VERSION_MINOR);  
16:    fprintf(stdout,"Usage: %s number\n",argv[0]);  
17:    return 1;  
18:    }  
19:   double inputValue = atof(argv[1]);  
20:  #ifdef USE_MYMATH  
21:   double outputValue = mysqrt(inputValue);  
22:  #else  
23:   double outputValue = sqrt(inputValue);  
24:  #endif  
25:   fprintf(stdout,"The square root of %g is %g\n",  
26:       inputValue, outputValue);  
27:   return 0;  
28:  }

아래와 같이 소스코드(ex, TutorialConfig.h.in)에서도 CMakeLists에 정의한 option 변수에 대한 정의를 추가할 수 있다.

1:  #cmakedefine USE_MYMATH
728x90