Skip to content

Commit 71022d1

Browse files
authored
[Clang] [Docs] Add some CMake example code for linking against libclang (#166268)
Though we have a few code examples in our documentation that show how to *use* libclang, we never actually show how to *link* against it. I myself mostly figured this out through trial and error some time ago, and I’ve since had to explain it to others on several occasions, so I thought adding some very minimal CMake example code might be helpful.
1 parent 2286118 commit 71022d1

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

clang/docs/LibClang.rst

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ Code example
3838
3939
.. code-block:: cpp
4040
41+
// main.cpp
4142
#include <clang-c/Index.h>
4243
#include <iostream>
4344
@@ -57,6 +58,22 @@ Code example
5758
CXCursor cursor = clang_getTranslationUnitCursor(unit); //Obtain a cursor at the root of the translation unit
5859
}
5960
61+
.. code-block:: cmake
62+
63+
# CMakeLists.txt
64+
cmake_minimum_required(VERSION 3.20)
65+
project(my_clang_tool VERSION 0.1.0)
66+
67+
# This will find the default system installation of Clang; if you want to
68+
# use a different build of clang, pass -DClang_DIR=/foobar/lib/cmake/clang
69+
# to the CMake configure command, where /foobar is the build directory where
70+
# you built Clang.
71+
find_package(Clang CONFIG REQUIRED)
72+
73+
add_executable(my_clang_tool main.cpp)
74+
target_include_directories(my_clang_tool PRIVATE ${CLANG_INCLUDE_DIRS})
75+
target_link_libraries(my_clang_tool PRIVATE libclang)
76+
6077
Visiting elements of an AST
6178
~~~~~~~~~~~~~~~~~~~~~~~~~~~
6279
The elements of an AST can be recursively visited with pre-order traversal with ``clang_visitChildren``.
@@ -283,6 +300,7 @@ Complete example code
283300

284301
.. code-block:: cpp
285302
303+
// main.cpp
286304
#include <clang-c/Index.h>
287305
#include <iostream>
288306
@@ -356,6 +374,21 @@ Complete example code
356374
);
357375
}
358376
377+
.. code-block:: cmake
378+
379+
# CMakeLists.txt
380+
cmake_minimum_required(VERSION 3.20)
381+
project(my_clang_tool VERSION 0.1.0)
382+
383+
# This will find the default system installation of Clang; if you want to
384+
# use a different build of clang, pass -DClang_DIR=/foobar/lib/cmake/clang
385+
# to the CMake configure command, where /foobar is the build directory where
386+
# you built Clang.
387+
find_package(Clang CONFIG REQUIRED)
388+
389+
add_executable(my_clang_tool main.cpp)
390+
target_include_directories(my_clang_tool PRIVATE ${CLANG_INCLUDE_DIRS})
391+
target_link_libraries(my_clang_tool PRIVATE libclang)
359392
360393
.. _Index.h: https://github.com/llvm/llvm-project/blob/main/clang/include/clang-c/Index.h
361394

0 commit comments

Comments
 (0)