The Complete Guide to Clang and LLVM for C and C++
Clang and LLVM from first compile to production: architecture, diagnostics, sanitizers, clangd, clang-tidy, coverage, ThinLTO, cross-compiling and tools.

Clang is a C, C++ and Objective-C compiler front end, and LLVM is the compiler infrastructure behind it: an intermediate representation, an optimizer, code generators for dozens of CPUs, a linker and a set of tools that replace most of the GNU binutils. Together they ship as the system compiler on macOS and FreeBSD, as the default compiler for Android and for much of Google's and Apple's software, and as an installable alternative to GCC on every Linux distribution. For many C and C++ developers the practical reasons to learn it are specific: clearer diagnostics, the sanitizers, clangd and clang-tidy for editor and CI work, source-based coverage, ThinLTO and a toolchain that cross-compiles to any target from one binary.
This guide is a working tour for developers who already compile C or C++ with GCC and want to use the LLVM ecosystem well. It starts with the architecture, because every tool makes sense once you know where it sits in the pipeline. Then it covers installing and switching compilers, reading the diagnostics, the optimizer and its reports, the sanitizers, the editor and linting tools, coverage, link-time optimization, lld, libc++, cross-compiling, the IR tools and the release process. Every section has commands and the output they print. The text follows the LLVM 18 and Clang 18 documentation, and notes where an option is newer or older. Examples run on x86-64 Linux unless stated.
How to read this guide
You do not need all of it at once. If you only want to swap gcc for clang in a build, read the first four sections and the compatibility section. If you want better bug-finding, jump to the sanitizers and the static analysis section. If you work on embedded or multi-platform code, read the cross-compiling section and the IR tools. The decision table near the end collects which tool answers which question, and the final sections list the mistakes that cost the most time.
The architecture: front end, IR, back end
A compiler built on LLVM has three stages, and the boundaries between them are the design's core idea.
The front end parses source text and produces LLVM IR. Clang is the front end for C, C++ and Objective-C. Other front ends exist for Rust (rustc), Swift, Zig, Julia and more, and all of them hand IR to the same optimizer and back ends. That sharing is the reason an optimization written once in LLVM benefits every language.
The middle end is the optimizer. LLVM IR is a typed, low-level, static-single-assignment language: every value is assigned once, memory is explicit, and control flow is a graph of basic blocks. The optimizer is a sequence of passes over that IR, such as inlining, loop vectorization and dead code elimination, run by the pass manager. You can run any of them by hand with opt.
The back end turns optimized IR into machine code for a target. It selects instructions, allocates registers, schedules and emits assembly or an object file. llc runs the back end alone. Clang calls it internally, and a linker, normally lld, joins the objects into an executable.
The pipeline for clang -O2 hello.c -o hello is therefore: preprocess and parse with Clang, generate IR, optimize it, generate machine code, assemble and link. Each stage is available separately, which is what makes the tools below possible. The documentation uses the words "bitcode" for the on-disk binary form of IR and .ll for its textual form.
You can see each stage's output with flags. Here is a tiny program and the first two views of it:
#include <stdio.h>
int square(int x)
{
return x * x;
}
int main(void)
{
printf("%d\n", square(7));
return 0;
}clang -E hello.c | tail -n 12int square(int x)
{
return x * x;
}
int main(void)
{
printf("%d\n", square(7));
return 0;
}-E stops after the preprocessor, and the long expansion of stdio.h precedes the lines shown. The next stage is IR:
clang -O0 -S -emit-llvm hello.c -o hello.ll
grep -A4 'define.*@square' hello.lldefine dso_local i32 @square(i32 noundef %0) #0 {
%2 = alloca i32, align 4
store i32 %0, ptr %2, align 4
%3 = load i32, ptr %2, align 4
%4 = load i32, ptr %2, align 4At -O0 the IR is a literal translation, with every variable in an alloca. Attribute numbers and value names may differ slightly between versions. Later sections show what the optimizer does to it.
Installing and choosing a compiler
On macOS, clang is Apple's build of Clang, installed with the Xcode command line tools. Apple's version numbers do not match upstream's, so "Apple clang 15" is not "LLVM 15" and feature checks should use __has_feature and __has_builtin, not version macros. On Linux, install from the distribution (apt install clang lld clangd clang-tidy clang-format) or from the apt repository at apt.llvm.org that tracks the upstream releases, or download the binary tarballs from the LLVM releases page on GitHub. On Windows, the LLVM installer provides clang and clang-cl, a driver that accepts MSVC command-line options and links against the MSVC runtime.
Upstream publishes a major version about every six months, numbered 17, 18, 19 and so on, with point releases in between. Distribution packages usually add a version suffix, clang-18, and a symlink clang. Check what you have:
clang --versionclang version 18.1.8
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/binThe exact version and target triple depend on your system. The target triple has the form arch-vendor-os-environment, here x86_64-pc-linux-gnu. It is the single most important string in cross-compiling.
Selecting Clang for a build is usually one environment variable or one CMake flag. With Make and Autotools, CC=clang CXX=clang++ make. With CMake, -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++. With Meson, CC=clang CXX=clang++ meson setup build. To use LLVM's linker and archiver, add -fuse-ld=lld and set AR=llvm-ar, RANLIB=llvm-ranlib.
Compatibility with GCC
Clang aims to accept the same command-line options and the same dialect of C and C++ as GCC, including the GNU extensions. That goal is why many projects build with either compiler by changing one variable. In practice, almost every GCC flag you use daily works: -O2, -g, -Wall, -Wextra, -std=c11, -march=native, -fPIC, -pthread, -D, -I, -L and -l. The default language modes are -std=gnu17 for C and -std=gnu++17 for C++ in Clang 18, matching GCC 14.
To ease the transition Clang defines __GNUC__ as 4 and __GNUC_MINOR__ as 2, which makes headers that test for GCC take the GNU path, and also defines __clang__, __clang_major__ and __clang_minor__. Use __clang__ to detect Clang specifically, and never infer features from __GNUC__. A header that needs to know whether an attribute exists should test __has_attribute(name):
#include <stdio.h>
int main(void)
{
#ifdef __clang__
printf("clang %d.%d\n", __clang_major__, __clang_minor__);
#endif
#ifdef __GNUC__
printf("gnuc %d.%d\n", __GNUC__, __GNUC_MINOR__);
#endif
return 0;
}clang 18.1
gnuc 4.2Things that differ, and bite when you switch: some GCC-only flags such as -fno-aggressive-loop-optimizations or -Wno-stringop-overflow produce "unknown warning option" in Clang, so guard them with -Wno-unknown-warning-option or a build-system feature test. A few GCC extensions are absent, most famously nested functions in C, which Clang rejects, and variable-length arrays in structs. Pre-C23 __attribute__((optimize)) is ignored. Clang's diagnostics are stricter in places: a missing prototype, an implicit function declaration and an invalid conversion between pointer types are warnings or errors in Clang 16 and later where older compilers were silent, which breaks old autoconf configure scripts that probe with sloppy test programs. A later section on flags shows how to write a flag list that works with both.
Diagnostics worth the switch
Clang's error messages were a selling point from the start: they print the source line, a caret under the exact column, and a suggested fix where one is known.
#include <stdio.h>
int main(void)
{
int x;
printf("%d\n", x);
return 0;
}clang -Wall -c diag.cdiag.c:6:20: warning: variable 'x' is uninitialized when used here [-Wuninitialized]
6 | printf("%d\n", x);
| ^
diag.c:5:10: note: initialize the variable 'x' to silence this warning
5 | int x;
| ^
| = 0
1 warning generated.The second block is a "note" with a fix-it hint: the proposed edit, = 0, is shown under the caret. Editors and clang-tidy -fix can apply fix-its automatically. The format has used the | gutter since Clang 11, and the wording varies by version.
The warning set is larger than GCC's, and two options matter. -Wall -Wextra are the equivalent of GCC's. -Weverything enables every warning Clang has, including ones that are deliberately noisy or conflict with each other (for example -Wpadded and -Wunsafe-buffer-usage); use it to discover what exists, then subtract: -Weverything -Wno-padded -Wno-c++98-compat. Turn selected warnings into errors with -Werror=implicit-function-declaration, rather than -Werror globally, which breaks every compiler upgrade.
Colored output is on when the output is a terminal. Force it in CI logs with -fcolor-diagnostics. The option -fdiagnostics-show-template-tree helps with long C++ template errors by printing the type differences as a tree. For editors that parse errors, -fdiagnostics-format=json is not available, but clangd does the job properly, covered later.
The optimizer and what it tells you
-O0 disables optimization, -O1, -O2 and -O3 raise it, -Os and -Oz favor size, -Ofast adds unsafe math, and -Og is "optimize for debugging" since Clang 4. In LLVM, -O2 and -O3 run nearly the same pass pipeline, with different inlining thresholds and some loop transformations, so the gap between them is smaller than in GCC.
The most useful feature to learn early is optimization remarks. Clang can report what the optimizer did or declined to do, with -Rpass, -Rpass-missed and -Rpass-analysis, each taking a regular expression that selects the pass:
void scale(float *restrict out, const float *restrict in, int n)
{
for (int i = 0; i < n; i++)
out[i] = in[i] * 2.0f;
}clang -O2 -Rpass=loop-vectorize -Rpass-missed=loop-vectorize -c vec.cvec.c:3:5: remark: vectorized loop (vectorization width: 4, interleaved count: 4) [-Rpass=loop-vectorize]
3 | for (int i = 0; i < n; i++)
| ^The numbers depend on the target CPU: with -mavx2 the width becomes 8. The same mechanism reports inlining (-Rpass=inline), loop unrolling (-Rpass=unroll) and many more. To collect all remarks into a file instead of the terminal, add -fsave-optimization-record, which writes vec.opt.yaml, and view it with opt-viewer.py from the LLVM tree as an annotated HTML report.
Link-time optimization is first-class. -flto enables full LTO and -flto=thin enables ThinLTO, which does most of the cross-module inlining with parallel backends. Profile-guided optimization works with -fprofile-generate and -fprofile-use, with the profile merged by llvm-profdata. The posts on ThinLTO and PGO in this series go through the steps.
Compile-time cost is visible too. -ftime-trace, available since Clang 9, writes a JSON file per translation unit with the time spent in each phase and each template instantiation, in the Chrome trace format that chrome://tracing and Perfetto open:
clang++ -O2 -ftime-trace -c big.cpp -o big.o
ls big*big.cpp big.json big.oFor C++ code bases with slow builds, this one flag usually shows whether the time is in parsing headers, instantiating templates or optimizing, which decides whether precompiled headers, forward declarations or fewer templates is the right fix.
The sanitizers
LLVM's sanitizers are run-time checkers built into the compiler and a small runtime library. They cost a slowdown and extra memory, they are meant for testing, and they find bugs that tests alone miss. Each is enabled with -fsanitize=..., and all work best with -g for line numbers and -fno-omit-frame-pointer for stack traces. GCC supports most of them too, since the sanitizers were developed in LLVM and ported.
AddressSanitizer (-fsanitize=address) detects heap, stack and global buffer overflows, use-after-free, use-after-return and double free. It replaces malloc and surrounds allocations with poisoned redzones, tracked in shadow memory.
#include <stdlib.h>
int main(void)
{
int *a = malloc(4 * sizeof *a);
a[4] = 1; /* one past the end */
free(a);
return 0;
}clang -g -fsanitize=address asan.c -o asan && ./asan==4127==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x604000000020 at pc 0x0000004c1234 bp 0x7ffd1b2c3d40 sp 0x7ffd1b2c3d38
WRITE of size 4 at 0x604000000020 thread T0
#0 0x4c1233 in main asan.c:6:10
0x604000000020 is located 0 bytes after 16-byte region [0x604000000010,0x604000000020)
allocated by thread T0 here:
#0 0x49a0fd in malloc
#1 0x4c11fb in main asan.c:5:14
SUMMARY: AddressSanitizer: heap-buffer-overflow asan.c:6:10 in mainThe process ID, the addresses and the trace depth will differ on every run; the structure is stable: the kind of error, the access, where the memory was allocated. A fatal report exits the process with status 1.
UndefinedBehaviorSanitizer (-fsanitize=undefined) checks signed integer overflow, shifts, null dereference, misaligned access, invalid enum values and more. It reports and, by default, continues:
#include <limits.h>
#include <stdio.h>
int main(void)
{
int x = INT_MAX;
printf("%d\n", x + 1);
return 0;
}ubsan.c:7:22: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
-2147483648Clang adds unsigned-integer-overflow and implicit-conversion checks (-fsanitize=unsigned-integer-overflow, -fsanitize=implicit-conversion) that are not undefined behavior in C but often indicate bugs.
ThreadSanitizer (-fsanitize=thread) detects data races between threads and cannot be combined with AddressSanitizer in the same binary. MemorySanitizer (-fsanitize=memory, Clang only) detects use of uninitialized memory, and requires that all code, including the C++ standard library, be instrumented, which makes it harder to deploy. LeakSanitizer is part of AddressSanitizer on Linux and prints leaks at exit.
The fuzzing support in LLVM, libFuzzer, links the fuzz target with -fsanitize=fuzzer. You provide one function:
#include <stddef.h>
#include <stdint.h>
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
if (size >= 4 && data[0] == 'F' && data[1] == 'U' && data[2] == 'Z' && data[3] == 'Z')
__builtin_trap();
return 0;
}clang -g -fsanitize=fuzzer,address fuzz.c -o fuzz && ./fuzzThe fuzzer generates inputs, learns from the coverage it gets, and finds the four-byte trigger within a short time; it then prints a crash report and writes the input to a file named crash-<hash>. The hash and the time differ per run.
A set of other options builds on the same machinery for production hardening: -fstack-protector-strong, -D_FORTIFY_SOURCE=3 with optimization, -fsanitize=cfi for control-flow integrity (requires -flto and -fvisibility=hidden) and -fsanitize=safe-stack. These are not testing tools; they ship in release builds in browsers and Android.
Editor and code-quality tools
The Clang front end is available as a library, and LLVM ships tools built on it that understand your code the way the compiler does. Three matter in daily work.
clangd
clangd is a language server: it speaks the Language Server Protocol to editors such as VS Code, Neovim, Emacs and CLion, and provides completion, go-to-definition, find-references, diagnostics, rename and fix-its using the real Clang parser. Because it parses with the same flags as your build, it needs to know them, and it reads them from a compilation database named compile_commands.json, which build systems can generate. In CMake add -DCMAKE_EXPORT_COMPILE_COMMANDS=ON, and the file appears in the build directory; point clangd at it by symlinking it to the source root or passing --compile-commands-dir=build. Meson and Bazel have their own generators, and bear -- make records one from any Makefile build. A dedicated post covers each of these.
A project-level .clangd file configures it, for instance to add flags that your build does not pass:
CompileFlags:
Add: [-Wall, -Wextra]
Diagnostics:
UnusedIncludes: Strictclang-tidy
clang-tidy is a linter and refactoring tool with a few hundred checks in families such as bugprone-*, performance-*, readability-*, modernize-*, cppcoreguidelines-* and clang-analyzer-*. It parses each file with your flags and reports issues, many with automatic fixes.
#include <string.h>
int copy_name(char *dst, const char *src)
{
strncpy(dst, src, strlen(src));
return 0;
}clang-tidy tidy.c -checks='bugprone-*' -- -std=c11tidy.c:5:5: warning: the length argument of 'strncpy' depends on the source ('strlen(src)'); this does not bound the destination [bugprone-not-null-terminated-result]
5 | strncpy(dst, src, strlen(src));
| ^
1 warning generated.The check names and wording vary by version. Everything after -- is the compile command. Run it over a whole project with run-clang-tidy -p build, which reads the compilation database and runs in parallel. Add a .clang-tidy file at the repository root to fix the check list for the team, and treat the first run as a triage session: enable the families you care about and turn the others off. Apply fixes with -fix, and review the diff.
clang-format
clang-format rewrites source to a defined style, from a .clang-format file. Predefined bases are LLVM, Google, Chromium, Mozilla, WebKit, Microsoft and GNU, and you override individual options. Run it in CI with --dry-run --Werror to fail on unformatted code, and in the editor on save. A short post in this series covers a configuration that does not start style arguments.
The static analyzer
Clang also contains a path-sensitive static analyzer that explores execution paths through a function and across functions in a translation unit and reports bugs such as null dereference, use after free, memory leaks and division by zero. Run it with scan-build make, which wraps your build, or clang --analyze file.c, or through clang-tidy -checks='clang-analyzer-*'. A dedicated post shows scan-build in detail, with its HTML report.
Source-based code coverage
Clang implements coverage at the source level, using a mapping from regions of source to counters, which makes the report accurate for macros, templates and short-circuit expressions. Compile with -fprofile-instr-generate -fcoverage-mapping, run the program, merge the raw profile and report:
#include <stdio.h>
int classify(int n)
{
if (n < 0)
return -1;
if (n == 0)
return 0;
return 1;
}
int main(void)
{
printf("%d\n", classify(5));
return 0;
}clang -fprofile-instr-generate -fcoverage-mapping cov.c -o cov
LLVM_PROFILE_FILE=cov.profraw ./cov
llvm-profdata merge -sparse cov.profraw -o cov.profdata
llvm-cov report ./cov -instr-profile=cov.profdataFilename Regions Missed Regions Cover Functions Missed Functions Executed Lines Missed Lines Cover
cov.c 6 2 66.67% 2 0 100.00% 11 2 81.82%
TOTAL 6 2 66.67% 2 0 100.00% 11 2 81.82%The numbers follow from the code: two return paths, -1 and 0, never ran. The report layout is stable across versions, while the exact columns grew slightly in newer releases. For a line-by-line view, llvm-cov show ./cov -instr-profile=cov.profdata prints the source with execution counts, and llvm-cov show -format=html -output-dir=cov-html writes a browsable report. The profile file is the same mechanism as profile-guided optimization, so the two can share a profiling run.
The linker, lld
lld is LLVM's linker, a drop-in replacement for GNU ld on ELF, a replacement for link.exe on Windows and for ld64 on macOS. It is much faster than GNU ld on large links, supports ThinLTO natively and shares options with GNU ld. Use it with -fuse-ld=lld. On many Linux distributions it is a separate package, lld. To make it your default for a build, set LDFLAGS=-fuse-ld=lld or the CMake variable CMAKE_EXE_LINKER_FLAGS=-fuse-ld=lld.
clang -O2 -fuse-ld=lld hello.c -o hello
readelf -p .comment helloString dump of section '.comment':
[ 0] Linker: LLD 18.1.8
[ 1b] clang version 18.1.8The .comment section records which tools made the binary, which is a quick check that the link used lld. Related tools complete the set: llvm-ar and llvm-ranlib for archives, llvm-nm, llvm-objdump, llvm-readelf, llvm-size, llvm-strip and llvm-objcopy for inspection and editing, and llvm-symbolizer for turning addresses into source lines, which the sanitizers call themselves.
The C++ standard library, libc++
On Linux, Clang uses the GNU C++ library libstdc++ by default, because that is what the system's other C++ code uses. LLVM has its own implementation, libc++, selected with -stdlib=libc++. It is the default on macOS and on FreeBSD. Mixing the two in one process is an ABI hazard, since a std::string from one is not the other, so decide per project and rebuild all C++ dependencies. A post in this series compares them.
clang++ -std=c++20 -stdlib=libc++ hello.cpp -o hello -lc++abiThe exact link libraries depend on how libc++ was built and packaged; on Debian and Ubuntu the packages libc++-dev and libc++abi-dev provide them. LLVM's compiler-rt replaces libgcc with -rtlib=compiler-rt, and libunwind replaces the GNU unwinder, which together produce a toolchain with no GNU runtime, as Android and Fuchsia use.
Cross-compiling
A single Clang binary can generate code for every target it was built with, so cross-compiling needs no separate toolchain, only a sysroot with the target's headers and libraries. Select the target with --target (or -target) and a triple, and the sysroot with --sysroot:
clang --target=aarch64-linux-gnu --sysroot=/opt/sysroots/aarch64 -fuse-ld=lld -O2 hello.c -o hello-arm64
file hello-arm64hello-arm64: ELF 64-bit LSB pie executable, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux-aarch64.so.1, for GNU/Linux 3.7.0, not strippedList the targets your build supports with clang --print-targets. For bare-metal embedded work, a typical command is clang --target=armv7em-none-eabi -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16 -nostdlib -c startup.c, with the Arm GNU Toolchain's newlib or LLVM's own picolibc-based builds supplying the libraries. Zig uses Clang the same way, and zig cc bundles the sysroots so that zig cc -target aarch64-linux-musl needs nothing else installed.
If you cross-compile, check the host assumptions in your build: CMake needs a toolchain file with CMAKE_SYSTEM_NAME, CMAKE_C_COMPILER_TARGET and CMAKE_SYSROOT; Autotools needs --host=aarch64-linux-gnu. A later post series covers cross-compiling in depth.
The IR toolchain
Because the pipeline is modular, you can work on IR directly. These tools are the ones the LLVM documentation lists first.
clang -S -emit-llvmwrites textual IR (.ll), and-c -emit-llvmwrites bitcode (.bc).optruns optimization and analysis passes on IR.opt -passes='mem2reg,instcombine' -S in.ll -o out.ll. A post covers it.llccompiles IR to assembly or an object file for a chosen target. A post covers it.llvm-asandllvm-disconvert between text and bitcode.llvm-mcassembles and disassembles machine code with the LLVM assembler.lliinterprets or JIT-compiles IR and runs it, which is useful for tiny experiments.llvm-linkmerges bitcode modules.
A short round trip shows how they fit:
clang -O0 -S -emit-llvm -Xclang -disable-O0-optnone hello.c -o hello.ll
opt -passes='mem2reg,instcombine' -S hello.ll -o hello.opt.ll
grep -A3 'define.*@square' hello.opt.lldefine dso_local i32 @square(i32 noundef %0) #0 {
%2 = mul nsw i32 %0, %0
ret i32 %2
}The alloca, store and load instructions disappeared, and the function is a multiplication. The nsw flag means "no signed wrap", the IR's record of the fact that signed overflow is undefined, which later passes use. The -Xclang -disable-O0-optnone option prevents Clang from marking -O0 functions as non-optimizable, which would make opt skip them.
Writing flags that work with both compilers
Projects that must build with GCC and Clang keep a flag list that is the intersection plus conditional additions. Do not branch on __GNUC__ or a version number; test the compiler. In CMake, check_c_compiler_flag and check_cxx_compiler_flag try a flag and set a variable. In CMake the check looks like this:
include(CheckCCompilerFlag)
set(MY_WARNINGS -Wall -Wextra -Wshadow)
check_c_compiler_flag(-Wunused-but-set-variable HAVE_WUBSV)
if(HAVE_WUBSV)
list(APPEND MY_WARNINGS -Wunused-but-set-variable)
endif()
target_compile_options(app PRIVATE ${MY_WARNINGS})A dedicated post in this series builds a cleaner approach for Make and Meson too. The general rules: use -Wno-unknown-warning-option with Clang so a GCC-only -Wno- flag does not error, use -Wno-error=... selectively, and keep sanitizer options identical across the two where possible.
The release process and versions
LLVM branches a release roughly every six months, in March and September, with release candidates before each and point releases afterwards. A major version changes C++ standard support, adds warnings and checks, and removes deprecated options. The release notes at releases.llvm.org list user-visible changes, and a post in this series summarizes the notable changes in LLVM 18 for C and C++ developers. Pin the compiler in CI with the exact major version, clang-18, and upgrade deliberately: new warnings appear in new releases and break -Werror builds.
Understanding the target triple
Every Clang invocation compiles for a target, named by a triple of the form arch-vendor-os-environment, where the vendor field is often omitted or unknown. The examples are x86_64-pc-linux-gnu, aarch64-apple-darwin, armv7em-none-eabi, riscv64-unknown-linux-gnu and x86_64-pc-windows-msvc. The first part selects the instruction set, the third the operating system and thus the object format and system calls, and the fourth the ABI and C library: gnu for glibc, musl for musl, eabi for bare-metal Arm, msvc for the Microsoft runtime. Print the default with clang -dumpmachine, and print everything the compiler assumes for a target with clang --target=aarch64-linux-gnu -dM -E - < /dev/null, which lists the predefined macros such as __aarch64__, __LP64__ and __ELF__. When a cross-build mis-detects the platform, this macro list tells you what the compiler believes.
CPU selection is separate. -march=native tunes for the machine you build on, -mcpu=cortex-a72 selects an Arm core, and -march=x86-64-v3 selects an x86-64 feature level with AVX2 and BMI2. The same IR can be lowered to any of them, which is how a package builder produces binaries for several microarchitectures from one source tree.
Debugging with LLDB
LLVM's debugger, lldb, is the default on macOS and works on Linux and Windows. Its command set differs from GDB's, but the mapping is regular. Compile with -g and -O0 for the clearest results:
clang -g -O0 hello.c -o hello
lldb ./hello(lldb) target create "./hello"
Current executable set to '/home/dev/hello' (x86_64).
(lldb) breakpoint set --name square
Breakpoint 1: where = hello`square + 11 at hello.c:4:12, address = 0x0000000000401136
(lldb) run
Process 5821 launched: '/home/dev/hello' (x86_64)
Process 5821 stopped
* thread #1, name = 'hello', stop reason = breakpoint 1.1
frame #0: 0x0000000000401136 hello`square(x=7) at hello.c:4:12
(lldb) frame variable
(int) x = 7
(lldb) bt
* thread #1, name = 'hello', stop reason = breakpoint 1.1
* frame #0: 0x0000000000401136 hello`square(x=7) at hello.c:4:12
frame #1: 0x000000000040115e hello`main at hello.c:9:20Process IDs and addresses are examples. The short forms are what you type daily: b square sets a breakpoint, r runs, n steps over, s steps in, c continues, bt prints the stack, p x prints an expression and fr v prints the frame's variables. The table of GDB equivalents is on the LLDB site, and lldb also reads .lldbinit for settings and Python scripts for pretty printers. For core files, lldb -c core ./hello works the same way. GDB still debugs Clang-built programs, since the DWARF debug information follows the standard; use -g and -gdwarf-4 or -gdwarf-5 as your debugger needs.
A small project, end to end
The pieces above combine into a short workflow for a new C project, which is a good way to see them working together. Start with a CMake file that exports the compilation database and turns on warnings:
cmake_minimum_required(VERSION 3.20)
project(demo C)
set(CMAKE_C_STANDARD 17)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_executable(demo main.c util.c)
target_compile_options(demo PRIVATE -Wall -Wextra -Wshadow)Configure with Clang and an optional sanitizer, then build:
cmake -S . -B build -DCMAKE_C_COMPILER=clang -DCMAKE_C_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g"
cmake --build build
ln -sf build/compile_commands.json .The last line makes the compilation database visible to clangd and clang-tidy at the repository root. The sanitized binary runs your tests with memory and undefined-behavior checking, the editor gets accurate navigation and the linter gets the same flags the build used. Add run-clang-tidy -p build and clang-format --dry-run --Werror to CI and the project has a baseline of quality checks that costs a few lines of configuration. When a coverage question comes up, add a separate build directory with the instrumentation flags, and keep the sanitizer and coverage builds apart, since both rewrite the program.
Errors you meet when switching from GCC
A handful of messages account for most of the first day with Clang on an existing code base. Read each one as information about the code.
The first is error: call to undeclared function 'foo'; ISO C99 and later do not support implicit function declarations. Clang 16 made this an error by default in C99 and later modes, where GCC only warned. The fix is to include the right header, and for an old configure script that probes with a program lacking a prototype, to pass -Wno-implicit-function-declaration in the probe's flags, or upgrade the script. The second is error: incompatible function pointer types or the matching -Wincompatible-function-pointer-types, promoted to an error in Clang 16 as well, which flags callbacks with the wrong signature, a real bug that the old compiler let through.
A third is warning: unknown warning option '-Wno-stringop-overflow', from a GCC-only flag in a shared build file; add -Wno-unknown-warning-option before it, or guard it with a feature check. Fourth: error: use of undeclared identifier for a function defined later in a C++ file, where GCC's two-phase lookup in templates was more permissive, which you fix by declaring or qualifying the name. Fifth: linker errors mentioning libstdc++ symbols when a program is built with -stdlib=libc++ but links an object built the other way. And finally, C++ code that relied on #include <bits/stdc++.h>, a GCC-specific header, fails on macOS and with libc++, where the header does not exist; replace it with the specific standard headers.
None of these are Clang bugs. They are places where the project depended on behavior the standard does not promise, and Clang's stricter default is a useful early warning for a future GCC release.
Looking inside the compiler
Because Clang is a library, it can show its working at every stage, which is the fastest way to settle an argument about what a piece of code means. The abstract syntax tree is one flag away:
int twice(int v) { return v + v; }clang -Xclang -ast-dump -fsyntax-only ast.cTranslationUnitDecl 0x55d3c8a1b0a8 <<invalid sloc>> <invalid sloc>
`-FunctionDecl 0x55d3c8a5e3b8 <ast.c:1:1, col:34> col:5 twice 'int (int)'
|-ParmVarDecl 0x55d3c8a5e2f0 <col:11, col:15> col:15 used v 'int'
`-CompoundStmt 0x55d3c8a5e548 <col:18, col:34>
`-ReturnStmt 0x55d3c8a5e538 <col:20, col:31>
`-BinaryOperator 0x55d3c8a5e518 <col:27, col:31> 'int' '+'
|-ImplicitCastExpr 0x55d3c8a5e4e8 <col:27> 'int' <LValueToRValue>
| `-DeclRefExpr 0x55d3c8a5e4a8 <col:27> 'int' lvalue ParmVar 0x55d3c8a5e2f0 'v' 'int'
`-ImplicitCastExpr 0x55d3c8a5e500 <col:31> 'int' <LValueToRValue>
`-DeclRefExpr 0x55d3c8a5e4c8 <col:31> 'int' lvalue ParmVar 0x55d3c8a5e2f0 'v' 'int'The hexadecimal pointers vary on every run. The structure is the useful part: the implicit LValueToRValue casts show where the language converts a variable into its value, which is exactly the information you need when a C++ overload or a template deduction surprises you. Use -Xclang -ast-dump=json for machine-readable output and -Xclang -ast-dump-filter=twice to limit it to one declaration in a large file. Other windows into the pipeline are -E for the preprocessor, -fdump-record-layouts (through -Xclang) for struct layout with offsets, -ftime-report for pass timings and -### to print the exact commands the driver would run, which is how you learn what clang passes to the assembler and linker on your platform:
clang -### hello.c -o hello 2>&1 | head -n 3clang version 18.1.8
Target: x86_64-pc-linux-gnu
Thread model: posixThe lines after the header are the cc1 frontend command, followed by the linker invocation, with every default flag the driver added made visible.
Hardening flags for release builds
A release build is the place to use Clang's mitigation options, which cost little at run time and raise the effort of exploiting a bug. A reasonable baseline for a Linux executable is -O2 -fstack-protector-strong -D_FORTIFY_SOURCE=2 -fPIE -pie -fstack-clash-protection -fcf-protection=full -Wl,-z,relro,-z,now. Each does one job. The stack protector places a canary before the return address in functions with arrays or address-taken locals, and aborts when it is overwritten. _FORTIFY_SOURCE needs optimization and makes the C library check buffer sizes in memcpy, sprintf and similar calls when the compiler knows the object size. -fPIE -pie lets the loader randomize the load address, -fstack-clash-protection probes the stack when large frames are allocated, -fcf-protection=full emits the instructions that Intel CET uses to enforce control flow on supported hardware, and relro with now makes the GOT read-only after relocation.
Clang adds options that GCC lacks or implements differently. -ftrivial-auto-var-init=zero, available without a special knob since Clang 16 and in GCC 12, zero-initializes automatic variables, closing a class of information leaks and uninitialized-use bugs at a measurable but small cost. -fsanitize=cfi with -flto and -fvisibility=hidden enforces forward-edge control-flow integrity, and -fsanitize=safe-stack splits the stack to protect return addresses from buffer overflows. Both are used in Chrome and Android. Check the flags took effect with checksec or readelf: the GNU_RELRO program header and BIND_NOW in the dynamic section show relro and now, and readelf -h shows the type DYN for a PIE.
Making builds faster
Compile time is the most common complaint about C++ and a fair one about large C projects, and the Clang ecosystem has several levers that stack. Start by finding out where the time goes with -ftime-trace, as shown earlier, because the right fix depends on the answer. If parsing headers dominates, a precompiled header helps: clang++ -x c++-header common.hpp -o common.hpp.pch builds one, and -include-pch common.hpp.pch uses it, and CMake's target_precompile_headers does the wiring for you. C++20 modules, supported in Clang 16 and later with build-system help from CMake 3.28, avoid reparsing altogether, though tooling support is still maturing and you should test it on your project before committing.
If template instantiation dominates, the trace shows which templates cost the most, and the usual remedies are extern template declarations for the common instantiations and fewer headers that pull in heavy libraries. If optimization dominates, lower the level for files that are not on the hot path, or use ThinLTO's cache. A compiler cache such as ccache or sccache skips unchanged work entirely and works with Clang by wrapping the compiler: CMAKE_C_COMPILER_LAUNCHER=ccache. Use lld for the link, which is often the slowest single step in an incremental build, and run ninja with enough jobs, since it parallelizes better than recursive Make. On a developer machine the combination of ccache, lld and Ninja turns a many-minute incremental build into seconds in the common case where one source file changed.
Choosing the right tool
| Question | Tool |
|---|---|
| Why is this loop not vectorized? | -Rpass-missed=loop-vectorize |
| Where does my program read out of bounds? | -fsanitize=address |
| Why is there signed overflow here? | -fsanitize=undefined |
| Is there a data race? | -fsanitize=thread |
| Which lines did the tests not run? | -fprofile-instr-generate -fcoverage-mapping, llvm-cov |
| What does the compiler think this expression means? | clang -Xclang -ast-dump |
| Why is my build slow? | -ftime-trace |
| How do I navigate code in my editor? | clangd with compile_commands.json |
| Which patterns are suspicious across the project? | clang-tidy, scan-build |
| How do I link faster? | -fuse-ld=lld, -flto=thin |
| How do I build for another CPU? | --target=<triple> with a sysroot |
| What machine code did this IR produce? | llc, llvm-objdump -d |
Mistakes that cost time
Assuming Apple clang is upstream clang. Features arrive in Apple's version on Apple's schedule, so check with
__has_featureand__has_attribute, not version numbers.Mixing sanitizers.
addressandthreadcannot be combined, andmemoryneeds an instrumented standard library. Run them as separate CI jobs.**Forgetting
-fno-omit-frame-pointer.** Sanitizer traces andperfcall graphs are poor without frame pointers.Linking C++ with the wrong standard library. A library built with
libstdc++and a program built withlibc++fail at link or, worse, at run time.**Using
-Weverythingwith-Werror.** Every Clang upgrade adds warnings, and the build breaks. Use it for discovery only.**Running
clang-tidywithout a compilation database.** It guesses the flags, resolves headers wrongly and reports false errors. Always pass-p build.Comparing optimizer output across versions. IR and assembly are not stable interfaces. Test behavior, not text.
Treating the optimizer as a black box. When a loop is slow, read the remarks before rewriting it.
When Clang is not the right choice
If your target is a niche microcontroller, GCC may have the only maintained back end, and a vendor SDK may support only its own GCC build. If you rely on a GCC-specific extension such as nested functions, you will find it missing. Some large legacy code bases depend on GCC's particular undefined-behavior outcomes. In those cases, use GCC and keep Clang for what it does uniquely well, such as the analyzer, clang-tidy and the sanitizers, which accept GCC-style command lines for analysis even when the product is built with another compiler.


