Using LLVM/Clang for Compilation

This chapter describes the basic knowledge of LLVM/Clang compilation and provides examples for demonstration. For more information about how to use Clang, run the clang --help command.

Overview

LLVM is a compiler that covers multiple programming languages and target processors. It uses Clang as the compiler and driver of C and C++. Clang can not only compile C and C++ programs into the LLVM intermediate representations (IRs), but also invoke all LLVM optimization passes for code generation until the final binary file is generated.

Multi-Version LLVM/Clang Installation

The openEuler OS provides standardized installation of the Clang/LLVM toolchain through its official Yum repository. To address diverse version requirements, the system implements a dual-version mechanism: installing a stable primary version by default while supporting additional secondary versions.

openEuler VersionPrimary LLVM VersionInstallation CommandSecondary VersionsInstallation Commands
22.03 LTS SP3LLVM12yum install -y clangLLVM17, LLVM18yum install -y llvm-toolset-17
yum install -y llvm-toolset-18
22.03 LTS SP4LLVM12yum install -y clangLLVM17, LLVM18yum install -y llvm-toolset-17
yum install -y llvm-toolset-18
24.03 LTSLLVM17yum install -y clangN/AN/A
24.03 LTS SP1LLVM17yum install -y clangLLVM18yum install -y llvm-toolset-18

To verify primary version installation on openEuler 22.03 LTS SP4:

shell
clang -v

clang version 12.0.1 (openEuler 12.0.1-6.oe2203sp4 f4a7df2c51fa9eb3679555ef2de92c638ba9f880)
Target: aarch64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/aarch64-linux-gnu/10.3.1
Found candidate GCC installation: /usr/lib/gcc/aarch64-linux-gnu/10.3.1
Selected GCC installation: /usr/bin/../lib/gcc/aarch64-linux-gnu/10.3.1
Candidate multilib: .;@m64
Selected multilib: .;@m64

To verify secondary version installation:

shell
source /opt/openEuler/llvm-toolset-17/enable
clang -v

clang version 17.0.6 ( 17.0.6-4.oe2203sp4)
Target: aarch64-openEuler-linux-gnu
Thread model: posix
InstalledDir: /opt/openEuler/llvm-toolset-17/root/usr/bin
System configuration file directory: /etc/llvm-toolset-17-clang/
Found candidate GCC installation: /usr/lib/gcc/aarch64-linux-gnu/10.3.1
Selected GCC installation: /usr/lib/gcc/aarch64-linux-gnu/10.3.1
Candidate multilib: .;@m64
Selected multilib: .;@m64

Successful installation is confirmed when the output displays the clang version information.

Practical Examples

Compile and execute C programs:

shell
clang [compiler-flags] hello.c -o hello.o
./hello.o

Compile and execute C++ programs:

shell
clang++ [compiler-flags] hello.cpp -o hello.o
./hello.o

To use LLVM's lld linker instead of the default gcc ld:

shell
clang [compiler-flags] -fuse-ld=lld hello.c -o hello.o
./hello.o

Building from Source

Refer to openEuler's llvm-project repository for manual build instructions.

Additional resources are available in LLVM User Guides.