CMake - 스크립트

mohadang·2022년 8월 11일
0

CMake

목록 보기
19/24
post-thumbnail

cmake에서 스크립트 파일을 사용할 수 있다.
스크립트 파일도 모듈과 같이 확장자가 .cmake이다

스크립트 실행

  • -P 옵션을 사용하여 스크립트 파일을 지정하면 실행 가능
# create-file.cmake

file(WRITE Hello.txt "Created by script")
[cmake-sources]> rm -f Hello.txt
[cmake-sources]> cmake -P script/create-file.cmake
[cmake-sources]> cat Hello.txt
Created by script

스크립트 파일 작성시 주의

  • cmake_minimum_required가 없으면 문제가 될 수 있다.
  • script.cmake
set("Jane Doe" "")
set(MYNAME "Jane Doe")

message("MYNAME: ${MYNAME}")    # Jane Doe 정상 출력

if("${MYNAME}" STREQUAL "")     # 그러나 MYNAME이 비어있다고 판단
  message("MYNAME is empty!")
endif()
[cmake-sources]> cmake -P minimum-required-bad/script.cmake
MYNAME: Jane Doe
CMake Warning (dev) at minimum-required-bad/script.cmake:6 (if):
  Policy CMP0054 is not set: Only interpret if() arguments as variables or
  keywords when unquoted.  Run "cmake --help-policy CMP0054" for policy
  details.  Use the cmake_policy command to set the policy and suppress this
  warning.

  Quoted variables like "Jane Doe" will no longer be\    # 경고 문구에서 출력
  dereferenced when the    
  policy is set to NEW.  Since the policy is not set the OLD behavior will be
  used.
This warning is for project developers.  Use -Wno-dev to suppress it.

MYNAME is empty!    # MYNAME이 설정되지 않았다고 출력
  • 스크립트를 정상적으로 실행 시키기 위해서는 cmake_minimum_required을 지정하면 된다
cmake_minimum_required(VERSION 3.1)

set("Jane Doe" "")
set(MYNAME "Jane Doe")

message("MYNAME: ${MYNAME}")

if("${MYNAME}" STREQUAL "")
  message("MYNAME is empty!")
endif()
[cmake-sources]> cmake -P minimum-required-good/script.cmake
MYNAME: Jane Doe

시스템 명령

  • 스크립트는 시스템 명령어를 실행할 수 있다.
if(WIN32)
  # 'rmdir' will exit with error if directory doesn't exist
  # so we have to put 'if' here
  if(EXISTS "${dir_to_remove}")
    # need to convert to windows-style path
    file(TO_NATIVE_PATH "${dir_to_remove}" native_path)
    execute_process(        # 시스템 명령어 실행
        COMMAND cmd /c rmdir "${native_path}" /S /Q
        RESULT_VARIABLE result
    )
  endif()
else()
  # no need to put 'if', 'rm -rf' produce no error if directory doesn't exist
  execute_process(        # 시스템 명령어 실행
      COMMAND rm -rf "${dir_to_remove}"
      RESULT_VARIABLE result
  )
endif()
  • 시스템 명령을 사용하여 스크립트를 작성할 수 있지만 OS 플랫폼 의존적인 코드를 작성하게 되었다.
  • 시스템 명령을 직접 사용하기보다는 cmake 명령을 사용하는것을 권고 한다.

cmake 명령(-E)

  • -E 옵션을 사용하여 OS 플랫폼 독립적으로 명령어를 실행 할 수 있다.
red@DESKTOP-G15ND3V:~/cgold$ cmake -E
CMake Error: cmake version 3.18.2
Usage: cmake -E <command> [arguments...]
Available commands:
  capabilities              - Report capabilities built into cmake in JSON format
  cat <files>...            - concat the files and print them to the standard output
  chdir dir cmd [args...]   - run command in a given directory
  compare_files [--ignore-eol] file1 file2
                              - check if file1 is same as file2
  copy <file>... destination  - copy files to destination (either file or directory)
  copy_directory <dir>... destination   - copy content of <dir>... direct...
  copy_if_different <file>... destination  - copy files if it has changed
  echo [<string>...]        - displays arguments as text
  echo_append [<string>...] - displays arguments as text but no new line
  env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...
                            - run command in a modified environment
  environment               - display the current environment
  make_directory <dir>...   - create parent and <dir> directories
  md5sum <file>...          - create MD5 checksum of files
  sha1sum <file>...         - create SHA1 checksum of files
  sha224sum <file>...       - create SHA224 checksum of files
  sha256sum <file>...       - create SHA256 checksum of files
  sha384sum <file>...       - create SHA384 checksum of files
  sha512sum <file>...       - create SHA512 checksum of files
  remove [-f] <file>...     - remove the file(s), use -f to force ...
  remove_directory <dir>... - remove directories and their contents (d...
  rename oldname newname    - rename a file or directory (on one volume)
  rm [-rRf] <file/dir>...    - remove files or directories, use -f to for...
  server                    - start cmake in server mode
  sleep <number>...         - sleep for given number of seconds
  tar [cxt][vf][zjJ] file.tar [file/dir1 file/dir2 ...]
                            - create or extract a tar or zip archive
  time command [args...]    - run command and display elapsed time
  touch <file>...           - touch a <file>.
  touch_nocreate <file>...  - touch a <file> but do not create it.
  create_symlink old new    - create a symbolic link new -> old
  true                      - do nothing with an exit code of 0
  false                     - do nothing with an exit code of 1
  
  
-E 와 조합하여 사용할 수 있는 명령어중 remove_directory도 있다
  - remove_directory <dir>... - remove directories and their contents (...
  • cmake remove_directory 명령어 실행
red@DESKTOP-G15ND3V:~/cgold$ mkdir test
red@DESKTOP-G15ND3V:~/cgold$ cmake -E remove_directory test
red@DESKTOP-G15ND3V:~/cgold$ ls
CMakeLists.txt  bar  build  main.cc  modules  script.cmake
  • 스크립트 개선
cmake_minimum_required(VERSION 2.8)
project(foo NONE)

### OS 플랫폼 의존적인 코드는 걷어내고 코드가 간결해짐
execute_process(
    COMMAND "${CMAKE_COMMAND}" -E remove_directory "${CMAKE_CURRENT_BINARY_DIR}/__temp"
    RESULT_VARIABLE result
)

if(NOT result EQUAL 0)
  # Error
endif()

# CMAKE_COMMAND : /usr/local/bin/cmake
profile
mohadang

0개의 댓글