라이브러리 추가
제곱근 계산에 대한 구현이 포함된 라이브러리를 추가해보자.실행파일은 컴파일러가 제공해주는 표준 제곱근 함수대신 우리가 추가하는 라이브러리를 사용한다.이 튜토리얼을 위해서 MathFunctions 라는 하위 디렉토리를 생성한다.MathFunctions 디렉토리의 CMakeLists.txt 파일에 아래 내용을 추가하자mysqrt.cxx 파일에는 컴파일러가 제공하는 sqrt 함수와 비슷한 역할을 하는 mysqrt 함수가 존재한다.
1 add_library(MathFunctions mysqrt.cxx)cs
새로운 라이브러리 사용을 위해 최상위 CMakeLists.txt 파일에 add_subdirectory 호출을 해야한다. 또한 MathFunctions/mysqlrt.h 내에 함수 선언부를 찾을 수 있게 포함 디렉토리를 추가해야한다.
마지막으로 실행파일에 새로운 라이브러리를 추가한다.
123456 include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")add_subdirectory (MathFunctions)# add the executableadd_executable (Tutorial tutorial.cxx)target_link_libraries (Tutorial MathFunctions)cs 이제 MahFunctions 라이브러리를 옵션으로 선택할 수 있게해보자. 현재 시점에서 이 작업을 하는 이유는 아무것도 없지만, 스케일이 큰 작업을 할때에는 유용하게 사용할 수 있다.처음으로 할일은 최상위 CMakeLists.txt 파일에 option 을 추가하는것이다.다음으로 MathFunctions 라이브러리를 조건에 따라 빌드와 링크에 반영되게 한다.
123 # should we use our own math functions?option (USE_MYMATH"Use tutorial provided math implementation" ON)cs 최상위 CMakeLists.txt 에서 할일은 이게 끝이다.
1234567891011 # 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 executableadd_executable (Tutorial tutorial.cxx)target_link_libraries (Tutorial ${EXTRA_LIBS})cs MathFunctions 을 사용하기 위해서 USE_MYMATH 라는 설정값을 사용한다. 실행파일에 선태적 라이브러리 링크를 위해 해당 라이브러리 정보를 수집하는 EXTRA_LIBS 라는 변수를 사용했다. 이것은 큰 프로젝트에서 많은 선택적 라이브러리를 깨끗하게 유지하는데 사용하는 일반적인 방법이다.위 설정에 따라 소스코드 또한 같이 수정되어야한다.
123456789101112131415161718192021222324252627282930313233 // 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"#endifint 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_MYMATHdouble outputValue = mysqrt(inputValue);#elsedouble outputValue = sqrt(inputValue);#endiffprintf(stdout,"The square root of %g is %g\n",inputValue, outputValue);return 0;}cs 소스코드에서 USE_MYMATH 를 사용할 수 있게 하기 위해 TutorialConfig.h.in 파일에 아래 내용을 추가한다.
1 #cmakedefine USE_MYMATHcs
WRITTEN BY
,