cmake - step 2

O.S/Linux 2015. 10. 23. 15:17
라이브러리 추가

제곱근 계산에 대한 구현이 포함된 라이브러리를 추가해보자. 
실행파일은 컴파일러가 제공해주는 표준 제곱근 함수대신 우리가 추가하는 라이브러리를 사용한다.
이 튜토리얼을 위해서 MathFunctions 라는 하위 디렉토리를 생성한다.
MathFunctions 디렉토리의 CMakeLists.txt 파일에 아래 내용을 추가하자

1
add_library(MathFunctions mysqrt.cxx)
cs

mysqrt.cxx 파일에는 컴파일러가 제공하는 sqrt 함수와 비슷한 역할을 하는 mysqrt 함수가 존재한다.

새로운 라이브러리 사용을 위해 최상위 CMakeLists.txt 파일에 add_subdirectory 호출을 해야한다. 또한 MathFunctions/mysqlrt.h 내에 함수 선언부를 찾을 수 있게 포함 디렉토리를 추가해야한다.

마지막으로 실행파일에 새로운 라이브러리를 추가한다.

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

이제 MahFunctions 라이브러리를 옵션으로 선택할 수 있게해보자. 현재 시점에서 이 작업을 하는 이유는 아무것도 없지만, 스케일이 큰 작업을 할때에는 유용하게 사용할 수 있다.
처음으로 할일은 최상위 CMakeLists.txt 파일에 option 을 추가하는것이다.

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

다음으로 MathFunctions 라이브러리를 조건에 따라 빌드와 링크에 반영되게 한다. 
최상위 CMakeLists.txt 에서 할일은 이게 끝이다.

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

MathFunctions 을 사용하기 위해서 USE_MYMATH 라는 설정값을 사용한다. 실행파일에 선태적 라이브러리 링크를 위해 해당 라이브러리 정보를 수집하는 EXTRA_LIBS 라는 변수를 사용했다. 이것은 큰 프로젝트에서 많은 선택적 라이브러리를 깨끗하게 유지하는데 사용하는 일반적인 방법이다.
위 설정에 따라 소스코드 또한 같이 수정되어야한다.

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

소스코드에서 USE_MYMATH 를 사용할 수 있게 하기 위해 TutorialConfig.h.in 파일에 아래 내용을 추가한다.

1
#cmakedefine USE_MYMATH
cs




WRITTEN BY
Profile
- 선빈 -


,