在源代码目录外编译clang例子

在源代码目录外编译clang例子

之前bitcode读写的例子编译一直报错,CMakeLists.txt改的面目全非,搜索过程中找到一个llvm工具编译的通用模版。

如何为独立的clang tool编写CMakeLists.txt

cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_PREFIX_PATH=/Users/fancy/Documents/LLVM/build/

DCMAKE_PREFIX_PATH指定你的llvm编译生成目录

CMakeLists.txt:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
cmake_minimum_required(VERSION 3.4.3)

set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Configs" FORCE)
set(CMAKE_SUPPRESS_REGENERATION TRUE)

############################################################
# setting Project informations
############################################################

set(PROJECT_NAME "llvm_bc_parsing_example")

set(LIBRARY_LIST )
set(LIBRARY_LIST ${LIBRARY_LIST} )
set(COMPONENT_LIST mcparser bitwriter bitreader support mc option )

############################################################
# generate makefiles
############################################################

project(${PROJECT_NAME})

find_package(LLVM REQUIRED CONFIG)
message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}")
message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}")

include_directories(${LLVM_INCLUDE_DIRS})
if(LLVM_BUILD_MAIN_SRC_DIR)
include_directories(${LLVM_BUILD_MAIN_SRC_DIR}/tools/clang/include)
include_directories(${LLVM_BUILD_BINARY_DIR}/tools/clang/include)
endif()
link_directories(${LLVM_LIBRARY_DIRS})
add_definitions(${LLVM_DEFINITIONS})

add_executable(${PROJECT_NAME} main.c)

if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
foreach(link_lib IN LISTS LIBRARY_LIST)
target_link_libraries(${PROJECT_NAME} optimized ${link_lib})
target_link_libraries(${PROJECT_NAME} debug ${link_lib}d)
endforeach()
else()
target_link_libraries(${PROJECT_NAME} ${LIBRARY_LIST})
set(CMAKE_CXX_FLAGS "-std=c99 -Wno-unused-parameter -fno-strict-aliasing -Weverything -Wno-switch-enum")
#set(CMAKE_EXE_LINKER_FLAGS "-static -static-libgcc -static-libstdc++")
endif()

llvm_map_components_to_libnames(llvm_libs ${COMPONENT_LIST})
target_link_libraries(${PROJECT_NAME} ${llvm_libs})

message(STATUS "User selected librarys = ${LIBRARY_LIST}")
message(STATUS "User selected components = ${COMPONENT_LIST}")
message(STATUS " = ${llvm_libs}")

COMPONENT_LIST添加你的代码需要的库名称(模块名就行,不需要完整的文件名)

https://heejune.me/2016/08/17/build-your-own-clang-example-outside-of-the-llvm-source-tree/

https://qiita.com/Chironian/items/8770c8ab833086fb51a9#328cmakeliststxt%E3%81%BE%E3%81%A8%E3%82%81