GCC 的扩展包括属性、内置函数、GNU 语言语法、预定义名字、pragma 和目标指令。它们并不是同一个层面的“C++ 功能”:有的只适用于 C,有的依赖处理器、对象文件格式或链接器。本文按 GCC 15.1 手册整理原来的十组内容;表中短片段是接口速查,完整程序在对应节给出。
本文的主机示例使用 Windows GCC 15.1.0;ARM 部分使用本机另一套 GCC 13.3.1、CMSIS 5.9.0,以 Cortex-M4 为目标只生成目标文件。这两种验证各有范围,不能从 Windows 编译成功推出 STM32 固件已经运行正确。
属性:声明的是承诺或目标要求
跳转到“属性:声明的是承诺或目标要求”GNU 属性常写为 __attribute__((name(arguments)))。C++ 标准也有 alignas、[[deprecated]]、[[noreturn]] 等设施;能用标准形式表达时,可优先考虑标准形式。
| 属性 | 典型写法 | 用途与边界 |
|---|---|---|
section | __attribute__((section(".ccmram"))) | 把对象/函数放入指定节;是否落在期望 RAM 由链接脚本与内存映射决定 |
aligned | __attribute__((aligned(32))) | 请求对齐;实际支持还受目标和链接器限制,不能仅凭声明推断 DMA 条件全满足 |
packed | struct __attribute__((packed)) Packet | 减少相应填充;成员可能未对齐,会改变 ABI,不能安全地当成任意平台的线格式直接解引用 |
weak | void handler(void) __attribute__((weak)); | 弱符号规则取决于目标格式与链接支持;覆盖处理函数还需检查实际链接结果 |
alias | void f(void) __attribute__((alias("g"))); | 别名目标通常须在同一翻译单元定义,类型应匹配;C++ 修饰名也需考虑 |
used | static int keep_me __attribute__((used)); | 要求编译器发出该对象;不保证链接器垃圾回收时仍保留 |
unused | int value __attribute__((unused)); | 抑制相应未使用警告;不是让变量失去语义 |
noinit | uint8_t buffer[64] __attribute__((noinit)); | GCC 此属性针对 ELF,依赖链接脚本布置 .noinit;保留内容还受启动代码与复位过程影响 |
constructor | void init(void) __attribute__((constructor)); | 在受支持的启动流程中于 main 前调用;不代替 C++ 类构造函数 |
destructor | void cleanup(void) __attribute__((destructor)); | 配合运行库的正常结束流程;裸机是否支持需确认,异常断电不属于此保证 |
interrupt | __attribute__((interrupt("IRQ"))) | 函数签名和生成的进入/返回序列与处理器有关,不能跨目标照抄 |
naked | __attribute__((naked)) | 不生成通常的函数序言/尾声;ARM GCC 只支持在这种函数中可靠使用基本 asm |
noreturn | __attribute__((noreturn)) | 承诺函数不正常返回;违反承诺不是一种可用的控制流技巧 |
optimize | __attribute__((optimize("O0"))) | 调整该函数优化选项;主要用于特殊测试/调试,不是修复错误代码的办法 |
always_inline | static inline ... __attribute__((always_inline)) | 对符合条件的调用强制尝试内联,失败可能诊断;不是无条件支持任意递归或间接调用 |
noinline | __attribute__((noinline)) | 禁止内联这一优化;不等于函数不会被其他优化处理 |
pure | __attribute__((pure)) | 返回值可依赖非 volatile 内存,但不能有可观察的外部副作用 |
const | __attribute__((const)) | 更严格:返回值不能依赖会变化的可观察内存状态;与 C++ 的 const 成员函数不同 |
hot | __attribute__((hot)) | 提供常执行的优化提示,不证明实际热点位置 |
cold | __attribute__((cold)) | 提供少执行的优化提示,可影响布局和优化策略 |
deprecated | __attribute__((deprecated("use new_api"))) | 在使用处给出弃用诊断 |
format | __attribute__((format(printf, 1, 2))) | 指定格式参数和可变参数位置,启用 printf 风格检查;索引要与真实声明匹配 |
pure 可以读取变化的非 volatile 全局对象,const 不能被这样使用;读取 volatile 寄存器、时间等有外部变化的状态,不应随意声明为这两种属性。constructor 与 C++ 静态对象构造的相对顺序也不能从名字推出。函数属性。
对 used,编译器发出对象和链接器保留节是两件事。受支持 ELF 环境的 retain、链接脚本 KEEP 等有各自条件;不要把 used 解释成“最终固件绝不会丢”。noinit 的条件尤其不能照搬到 Windows PE/COFF。变量属性、ARM 函数属性。
位操作内置函数
跳转到“位操作内置函数”没有 ll 后缀的这些接口通常接收 unsigned int 或 int,不能把其宽度无条件写成 32 位;ll 对应 unsigned long long 或 long long,也应查目标类型。字节交换接口则明确指定交换位数。位操作、字节交换。
| 函数 | 作用 | 前提或例子 |
|---|---|---|
__builtin_clz(x) | unsigned int 的前导零个数 | x 不能为 0;32 位时 0x00F00000u 对应 8 |
__builtin_clzll(x) | unsigned long long 的前导零个数 | x 不能为 0 |
__builtin_ctz(x) | unsigned int 的尾随零个数 | x 不能为 0;0xF00u 对应 8 |
__builtin_ctzll(x) | unsigned long long 的尾随零个数 | x 不能为 0 |
__builtin_popcount(x) | unsigned int 中的 1 位数量 | 0xFFu 对应 8;零输入可用 |
__builtin_popcountll(x) | unsigned long long 中的 1 位数量 | 0xFFULL 对应 8 |
__builtin_parity(x) | 1 位数量对 2 取余 | 0x11u 对应 0,表示偶数个 1 |
__builtin_parityll(x) | unsigned long long 的对应奇偶值 | 0x11ULL 对应 0 |
__builtin_ffs(x) | 最低 1 位的编号再加 1 | 0x08 对应 4;输入 0 返回 0 |
__builtin_ffsll(x) | long long 的对应位置 | 同样从 1 计数,零输入返回 0 |
__builtin_bswap16(x) | 交换 16 位值的两个字节 | 0x1234 → 0x3412 |
__builtin_bswap32(x) | 反转 32 位值中的字节顺序 | 0x12345678 → 0x78563412 |
__builtin_bswap64(x) | 反转 64 位值中的字节顺序 | 不等于反转每个字节内部的 bit |
clz(0)、ctz(0) 的结果未定义;需要处理零时先判断,或者在 C++20 中按实际需要采用 <bit> 的 std::countl_zero、std::countr_zero 等标准设施,不能把不同接口的零输入规则混用。
算术溢出检查
跳转到“算术溢出检查”这组内置函数计算数学结果,再检查它能否由结果指针所指类型表示。返回 true 表示溢出,false 表示可表示;计算本身不会先触发普通有符号加法的溢出行为。溢出检查规则。
| 函数 | 参数类型范围 | 运算 |
|---|---|---|
__builtin_add_overflow(a, b, result) | 通用整数实参;结果类型须符合接口要求 | 加法 |
__builtin_sub_overflow(a, b, result) | 同上 | 减法 |
__builtin_mul_overflow(a, b, result) | 同上 | 乘法 |
__builtin_uadd_overflow | unsigned int、unsigned int、unsigned int* | 加法 |
__builtin_usub_overflow | 同上 | 减法 |
__builtin_umul_overflow | 同上 | 乘法 |
__builtin_sadd_overflow | int、int、int* | 加法 |
__builtin_ssub_overflow | 同上 | 减法 |
__builtin_smul_overflow | 同上 | 乘法 |
下面合并验证位操作及九种算术接口。没有执行普通表达式 INT_MAX + 1,也没有把零传给 clz/ctz。
// gcc-bits-overflow.cpp — GCC#include <cassert>#include <cstdint>#include <iostream>#include <limits>
int main() { constexpr int uintBits = std::numeric_limits<unsigned int>::digits; constexpr int ullBits = std::numeric_limits<unsigned long long>::digits; static_assert(uintBits >= 24 && ullBits >= 56); assert(__builtin_clz(0x00F00000u) == uintBits - 24); assert(__builtin_clzll(0x00F0000000000000ULL) == ullBits - 56); assert(__builtin_ctz(0xF00u) == 8); assert(__builtin_ctzll(0x00000F0000000000ULL) == 40); assert(__builtin_popcount(0xFFu) == 8 && __builtin_popcountll(0xFFULL) == 8); assert(__builtin_popcount(0u) == 0); assert(__builtin_parity(0x11u) == 0 && __builtin_parityll(0x11ULL) == 0); assert(__builtin_ffs(0x08) == 4 && __builtin_ffsll(0x08LL) == 4); assert(__builtin_ffs(0) == 0 && __builtin_ffsll(0) == 0); assert(__builtin_bswap16(UINT16_C(0x1234)) == UINT16_C(0x3412)); assert(__builtin_bswap32(UINT32_C(0x12345678)) == UINT32_C(0x78563412)); assert(__builtin_bswap64(UINT64_C(0x123456789ABCDEF0)) == UINT64_C(0xF0DEBC9A78563412));
int result = 0; const int maximum = std::numeric_limits<int>::max(); const int minimum = std::numeric_limits<int>::min(); assert(!__builtin_add_overflow(40, 2, &result) && result == 42); assert(__builtin_add_overflow(maximum, 1, &result)); assert(!__builtin_sub_overflow(44, 2, &result) && result == 42); assert(__builtin_sub_overflow(minimum, 1, &result)); assert(!__builtin_mul_overflow(6, 7, &result) && result == 42); assert(__builtin_mul_overflow(maximum, 2, &result)); assert(!__builtin_sadd_overflow(40, 2, &result) && result == 42); assert(__builtin_sadd_overflow(maximum, 1, &result)); assert(!__builtin_ssub_overflow(44, 2, &result) && result == 42); assert(__builtin_ssub_overflow(minimum, 1, &result)); assert(!__builtin_smul_overflow(6, 7, &result) && result == 42); assert(__builtin_smul_overflow(maximum, 2, &result)); unsigned int unsignedResult = 0; const auto unsignedMaximum = std::numeric_limits<unsigned int>::max(); assert(!__builtin_uadd_overflow(40u, 2u, &unsignedResult) && unsignedResult == 42u); assert(__builtin_uadd_overflow(unsignedMaximum, 1u, &unsignedResult) && unsignedResult == 0u); assert(!__builtin_usub_overflow(44u, 2u, &unsignedResult) && unsignedResult == 42u); assert(__builtin_usub_overflow(0u, 1u, &unsignedResult) && unsignedResult == unsignedMaximum); assert(!__builtin_umul_overflow(6u, 7u, &unsignedResult) && unsignedResult == 42u); assert(__builtin_umul_overflow(unsignedMaximum, 2u, &unsignedResult)); std::cout << "bit builtins and nine overflow APIs: OK\n";}原子操作:旧接口的名字没有 builtin 前缀
跳转到“原子操作:旧接口的名字没有 builtin 前缀”原表的 __builtin_sync_* 拼写有误,正确接口为 __sync_*。GCC 手册将其归为旧接口,新 GCC 专用代码优先考虑带内存序参数的 __atomic_*,可移植 C++ 代码通常使用 <atomic>。旧原子接口。
| 正确函数 | 主要动作 | 返回值/顺序边界 |
|---|---|---|
__sync_fetch_and_add | 原子加 | 旧值 |
__sync_fetch_and_sub | 原子减 | 旧值 |
__sync_fetch_and_or | 原子按位或 | 旧值 |
__sync_fetch_and_and | 原子按位与 | 旧值 |
__sync_fetch_and_xor | 原子按位异或 | 旧值 |
__sync_add_and_fetch | 原子加 | 新值;变量名不能用 C++ 关键字 new |
__sync_bool_compare_and_swap | 相等时交换 | 是否交换成功 |
__sync_val_compare_and_swap | 相等时交换 | 操作前的值 |
__sync_synchronize | 完整内存屏障 | 无返回值 |
__sync_lock_test_and_set | 锁用交换 | 旧值;是 acquire 屏障,某些目标只支持设置为 1 |
__sync_lock_release | 释放对应锁 | 通常写 0;是 release 屏障 |
不能把最后两个接口也解释成完整双向屏障。处理器不直接支持某个宽度时,还可能需要运行库函数。下面是单线程返回值检查,不是锁实现或并发正确性证明。
// gcc-atomic-values.cpp — GCC#include <atomic>#include <cassert>#include <iostream>
int main() { unsigned int value = 10; assert(__sync_fetch_and_add(&value, 2u) == 10u && value == 12u); assert(__sync_fetch_and_sub(&value, 2u) == 12u && value == 10u); value = 0b1000; assert(__sync_fetch_and_or(&value, 0b0010u) == 0b1000u && value == 0b1010u); assert(__sync_fetch_and_and(&value, 0b1001u) == 0b1010u && value == 0b1000u); assert(__sync_fetch_and_xor(&value, 0b0011u) == 0b1000u && value == 0b1011u); value = 40; assert(__sync_add_and_fetch(&value, 2u) == 42u); assert(__sync_bool_compare_and_swap(&value, 42u, 7u) && value == 7u); assert(!__sync_bool_compare_and_swap(&value, 42u, 9u) && value == 7u); assert(__sync_val_compare_and_swap(&value, 7u, 8u) == 7u && value == 8u); __sync_synchronize(); unsigned int lock = 0; assert(__sync_lock_test_and_set(&lock, 1u) == 0u && lock == 1u); __sync_lock_release(&lock); assert(lock == 0u); std::atomic<unsigned int> standard{40}; assert(standard.fetch_add(2, std::memory_order_relaxed) == 40u); assert(standard.load(std::memory_order_relaxed) == 42u); std::cout << "legacy atomic return values and standard atomic: OK\n";}其他内置函数与 GNU 语言扩展
跳转到“其他内置函数与 GNU 语言扩展”| 内置函数 | 用途 | 不能忽略的限制 |
|---|---|---|
__builtin_expect(exp, c) | 给分支概率提供提示,返回转换后的 exp 值 | 不改变真值,也不保证提速;测量结果比猜测可靠 |
__builtin_constant_p(exp) | 查询编译器在当前选项下能否证明常量 | 返回 0 不证明表达式“绝不是常量”;结果可能依赖优化 |
__builtin_object_size(ptr, type) | 查询编译器能推断的对象范围 | 未知时有指定的哨兵结果;不是自动的运行时边界检查 |
__builtin_return_address(level) | 查询返回地址 | 与调用约定、内联和目标相关;非零层级尤其不可靠 |
__builtin_frame_address(level) | 查询帧地址 | 不适合作为通用栈遍历器;可受优化/目标影响 |
__builtin_alloca(size) | 在当前函数栈空间分配 | 大小必须受控,不能在函数返回后继续使用,也没有堆分配式失败恢复保证 |
__builtin_types_compatible_p(t1, t2) | 检查类型兼容性 | 此接口用于 C;C++ 用类型特征等合适设施 |
__builtin_choose_expr(c, e1, e2) | C 中按常量选择表达式 | C-only;没选中的分支仍须满足相关语法检查 |
__builtin_offsetof(T, member) | 获取成员偏移 | C++ 中仍须考虑标准布局等使用条件 |
__builtin_prefetch(addr, rw, locality) | 预取提示 | 地址表达式本身必须有效;提示不保证有指令或性能收益 |
| 语言扩展 | 语法示意 | C/C++ 边界 |
|---|---|---|
typeof / __typeof__ | __typeof__(x) y = x; | GNU 类型查询;C++ 标准接口为 decltype,推导规则不必完全相同 |
| 语句表达式 | ({ int value = 1; value + 1; }) | GNU 扩展;临时对象寿命等细节不能当成普通内联函数 |
| 零长度数组 | struct P { int len; char data[0]; }; | GNU 扩展;不是标准 C++ 动态数组,也不能替代分配和对象寿命管理 |
| case 范围 | case 'A' ... 'Z': | GNU 范围标签;端点编码及重叠范围需检查 |
| 数组指定初始化 | int a[10] = {[5] = 1, [8] = 2}; | C99/GNU C 用法;不能把 C++20 成员指定初始化等同于这种数组写法 |
| 复合字面量 | (struct Point){1, 2} | C99;GNU C++ 接受的相关扩展有不同的临时对象规则 |
| 标签值 | &&label 和 goto *target; | GNU computed goto;目标标签须在合适函数内,不能冒充普通函数指针 |
__restrict | int* __restrict target | 向优化器承诺相应无别名关系;违反承诺会破坏程序含义 |
__thread | __thread int tlsValue; | GNU 线程局部存储;与 C++ thread_local 的初始化能力不能完全等同 |
__int128 | unsigned __int128 wide; | 仅在有对应整数模式的目标提供;不是所有 32 位目标都有 |
GCC 明确把 C 的指定初始化扩展与 C++ 支持区分。指定初始化。下面文件有意使用 GNU C11,不要改成 .cpp 后仍把诊断归咎于缺少某个普通头文件。
// gcc-gnu-c.c — compile as GNU C11#include <assert.h>#include <stddef.h>#include <stdio.h>
struct Point { int x; int y; };struct Packet { unsigned int length; unsigned char data[0]; };static __thread int tlsValue;
static void copyThree(int* __restrict target, const int* __restrict source) { for (int i = 0; i < 3; ++i) target[i] = source[i];}
static int isUpper(char letter) { switch (letter) { case 'A' ... 'Z': return 1; default: return 0; }}
int main(void) { int x = 7; __typeof__(x) y = x; _Static_assert(__builtin_types_compatible_p(__typeof__(x), int), "int type"); const int selected = __builtin_choose_expr(1, 42, 99); const int expression = ({ int left = 1; int right = 2; left + right; }); int array[10] = {[5] = 1, [8] = 2}; struct Point point = (struct Point){1, 2}; assert(y == 7 && selected == 42 && expression == 3); assert(array[0] == 0 && array[5] == 1 && array[8] == 2); assert(point.x == 1 && point.y == 2 && isUpper('M') && !isUpper('0')); assert(__builtin_offsetof(struct Packet, data) >= sizeof(unsigned int)); const int source[3] = {1, 2, 3}; int target[3] = {0}; copyThree(target, source); // 两数组不重叠 assert(target[2] == 3); tlsValue = 9; assert(tlsValue == 9); char bytes[16] = {0}; assert(__builtin_object_size(bytes, 0) == sizeof(bytes)); assert(__builtin_constant_p(123) != 0); assert(__builtin_expect(x == 7, 1)); __builtin_prefetch(bytes, 0, 1); char* scratch = __builtin_alloca(16); for (int i = 0; i < 16; ++i) scratch[i] = (char)i; assert(scratch[15] == 15);#ifdef __SIZEOF_INT128__ unsigned __int128 wide = (unsigned __int128)1 << 64; assert((wide >> 64) == 1);#endif void* destination = &&finished; goto *destination;finished: puts("GNU C extensions and bounded builtins: OK"); return 0;}示例不把零长度数组当成可读写存储,也没有让 alloca 指针逃出函数。编译用 gcc -std=gnu11;启用严格 ISO -pedantic-errors 后,其中有意使用的 GNU 扩展会被拒绝。
预定义宏与函数内名字
跳转到“预定义宏与函数内名字”| 名字 | 含义 | 使用边界 |
|---|---|---|
__GNUC__ | GCC 兼容主版本号 | 其他编译器也可能定义它,不能单独证明编译器身份 |
__GNUC_MINOR__ | GCC 兼容次版本号 | 版本比较要与主版本号一起处理 |
__GNUC_PATCHLEVEL__ | 兼容补丁号 | 同样属于整组版本信息 |
__VERSION__ | 编译器版本描述字符串 | 适合诊断,不宜依赖字符串固定格式 |
__OPTIMIZE__ | 当前有相应优化设置 | 不证明某段代码已经得到某种优化 |
__OPTIMIZE_SIZE__ | 以代码大小为目标的优化设置 | 不能替代体积测量 |
__NO_INLINE__ | 普通内联相关的禁用/未优化设置 | 不宜外推成每个调用的最终机器码保证 |
__BYTE_ORDER__ | 目标字节序 | 与 __ORDER_LITTLE_ENDIAN__ 等比较 |
__SIZEOF_POINTER__ | 目标普通指针的字节数 | 是编译目标信息,不是运行主机型号 |
__ARM_ARCH | ARM 目标架构信息 | 非 ARM 目标可能未定义,先检查存在性 |
__thumb__ | ARM Thumb 编译模式 | 同样是目标相关条件 |
__FILE__ | 当前逻辑文件名 | 会受编译路径和 #line 等影响 |
__LINE__ | 当前逻辑行号 | 可用于诊断 |
__func__ | 当前函数名 | 标准规定的函数内名字,不是普通预处理宏 |
__FUNCTION__ | GCC 的相应函数名扩展 | 也不能当作普通字符串替换宏来拼接 |
__PRETTY_FUNCTION__ | GCC 的函数信息,C++ 中通常含签名 | 格式依语言和实现,不是稳定业务标识 |
__DATE__ | 翻译时日期相关字符串 | 重现构建时还需考虑工具链时间控制 |
__TIME__ | 翻译时时间相关字符串 | 不等于程序实际启动时间 |
__TIMESTAMP__ | 源文件最后修改时间的字符串表示 | 不是简单的“当前编译时间戳” |
GCC 的函数名字说明把 __func__、__FUNCTION__、__PRETTY_FUNCTION__ 与预处理宏区分;宏可用预处理器展开,函数内这些名字按语言/编译器规则提供。函数名字、常用预定义宏。
pragma:把影响范围写清楚
跳转到“pragma:把影响范围写清楚”| 指令 | 典型形式 | 要点 |
|---|---|---|
| diagnostic | #pragma GCC diagnostic ignored "-Wunused-variable" | 使用 push/pop 限定诊断修改范围 |
| optimize | #pragma GCC optimize ("O0") | 影响其后的适用函数;不要靠它掩盖未定义行为 |
| target | #pragma GCC target ("...") | 选项字符串依目标;原来的 "thumb" 不能套用给 x86 编译器 |
| push_options | #pragma GCC push_options | 保存相关目标/优化选项 |
| pop_options | #pragma GCC pop_options | 恢复最近保存的选项 |
| reset_options | #pragma GCC reset_options | 恢复对应命令行选项状态 |
| message | #pragma message "building module" | 编译时信息,不是运行时输出 |
| warning | #pragma GCC warning "deprecated path" | 发出预处理诊断 |
| error | #pragma GCC error "unsupported configuration" | 让对应配置编译失败 |
| poison | #pragma GCC poison old_name | 禁止后续使用指定标识符,位置会影响包含文件 |
| pack | #pragma pack(push, 1) 与 #pragma pack(pop) | 改变成员布局/对齐,应成对恢复;和 packed 混用也需谨慎 |
未对齐成员指针不能被当成满足自然对齐的普通指针到处传递;访问协议缓冲区时,用明确的字节解析或 memcpy 等合适方法,并分别处理字节序。打包布局不会自动完成序列化。pragma 索引、结构布局 pragma。
内联汇编:给编译器完整描述
跳转到“内联汇编:给编译器完整描述”| 部分 | 形式 | 含义 |
|---|---|---|
| 基本 asm | __asm__("nop"); | 只有汇编模板,具体指令依目标 |
| 扩展 asm | __asm__(text : outputs : inputs : clobbers); | 描述输入、输出及其他被改状态 |
| 只写输出 | "=r"(result) | 结果由 asm 写入;若还要读旧值,不能只写 = |
| 只读输入 | "r"(value) | 编译器提供输入,不能暗中修改却不告知 |
| 读写操作数 | "+r"(counter) | 同一操作数既是输入也是输出 |
| clobber | "cc"、"memory" 或目标寄存器 | cc 表示标志状态,memory 告知额外内存影响;寄存器名字依目标 |
| volatile | __asm__ volatile(...) | 限制相应删除/移动优化;不自动成为线程同步或 CPU 内存屏障 |
| 约束 | 一般意义 | 例子与限制 |
|---|---|---|
r | 通用寄存器 | "r"(value);具体寄存器集合依目标 |
m | 内存操作数 | "m"(object);模板必须使用适合目标的访问形式 |
i | 立即数,包括适用的符号常量 | "i"(100) |
n | 编译时已知数值的立即数 | "n"(sizeof(int)) |
g | 允许的通用寄存器、内存或立即数 | 不是保证任何模板都接受这些形式 |
数字,如 0 | 与编号操作数匹配 | "0"(initial) 把输入绑定到第 0 个输出;编号不限于原表写出的 0~9 |
"memory" 是编译器层面对内存重排的约束,并不阻止 CPU 的所有推测访问;硬件同步还要使用目标指令及语言层面的正确同步关系。扩展 asm、简单约束。
下面只在 x86 GNU 编译器下演示无特权的 32 位加法,不能移到 ARM 后继续使用 addl。
// gcc-x86-asm.cpp — x86 GCC#include <cassert>#include <cstdint>#include <iostream>
#if !defined(__i386__) && !defined(__x86_64__)#error "This demonstration uses x86 instructions"#endif
std::uint32_t add(std::uint32_t left, std::uint32_t right) { std::uint32_t result; __asm__("addl %2, %0" : "=r"(result) : "0"(left), "r"(right) : "cc"); return result;}
std::uint32_t increment(std::uint32_t value) { __asm__("addl $1, %0" : "+r"(value) : : "cc"); return value;}
int main() { assert(add(40, 2) == 42); assert(add(UINT32_MAX, 1) == 0); assert(increment(41) == 42); assert(increment(UINT32_MAX) == 0); std::cout << "x86 asm constraints and modulo addition: OK\n";}Cortex-M:使用对应 CMSIS 接口
跳转到“Cortex-M:使用对应 CMSIS 接口”这一组是 ARM Cortex-M 场景,不是所有 GCC 平台的通用内置函数。CMSIS 名字需要正确的 CMSIS/设备头文件,处理器型号和特权状态还决定具体可用性。CMSIS CPU 指令。
| 原指令主题 | CMSIS 对应形式 | 作用 |
|---|---|---|
| NOP | __NOP() | 空操作 |
| WFI | __WFI() | 等待中断事件相关唤醒条件 |
| WFE | __WFE() | 等待事件 |
| SEV | __SEV() | 发送事件 |
| BKPT | __BKPT(0) | 触发调试断点行为 |
| DMB | __DMB() | 数据内存屏障 |
| DSB | __DSB() | 数据同步屏障 |
| ISB | __ISB() | 指令同步屏障 |
| CPSID | __disable_irq() | 设置可配置中断屏蔽相关状态 |
| CPSIE | __enable_irq() | 解除对应中断屏蔽相关状态 |
| MRS | __get_PRIMASK() 等 | 读取选定特殊寄存器,寄存器并非任意字符串参数 |
| MSR | __set_PRIMASK(value) 等 | 写选定特殊寄存器,受权限与寄存器规则约束 |
| REV | __REV(value) | 字节顺序反转 |
| CLZ | __CLZ(value) | 32 位前导零计数;不能把 CMSIS 的规则直接等同于 __builtin_clz |
下面是编译检查用的翻译单元,没有 main,不调用其中的等待、断点或中断控制函数。编译通过仅确认该工具链、选项和头文件组合接受这些声明及指令。
// cortex-m-instructions.c — Cortex-M4, compile only#include <stdint.h>#include "cmsis_gcc.h"
void instruction_examples(void) { __NOP(); __WFI(); __WFE(); __SEV(); __BKPT(0); __DMB(); __DSB(); __ISB(); __disable_irq(); __enable_irq();}
uint32_t read_interrupt_mask(void) { return __get_PRIMASK(); }void write_interrupt_mask(uint32_t value) { __set_PRIMASK(value); }uint32_t reverse_bytes(uint32_t value) { return __REV(value); }uint32_t count_leading_zeros(uint32_t value) { return __CLZ(value); }例如用 arm-none-eabi-gcc -std=gnu11 -mcpu=cortex-m4 -mthumb -I<自己的 CMSIS Core Include 目录> -c cortex-m-instructions.c 生成目标文件。尖括号部分是待替换的路径占位,不是可原样粘贴的目录。本文没有下载固件或执行这些硬件控制指令。
项目采用扩展时,应把编译模式、目标和验证命令固定在构建系统中。优先读取具体目标的手册与生成结果;速查表负责定位接口,不能替代 ABI、链接脚本、启动代码或并发设计。
来源:CSDN 原文,首次发布于 2025-08-24。