为何TCC无法生成自定义section?链接符号未定义问题
解决TCC编译自定义段时
__start_const_heap/__stop_const_heap未定义的问题 问题原因
TCC内置的轻量链接器不会像GCC/Clang依赖的GNU ld那样,自动为自定义段生成__start_<section>和__stop_<section>这类边界符号。尽管TCC支持section属性将变量放入自定义段,但自动生成段边界符号是GNU ld的专属扩展特性,TCC未实现该功能。
解决方案1:手动添加段边界标记(推荐)
在自定义段的开头和结尾分别放置占位变量,用它们的地址作为段的起始和结束边界:
#include <stdio.h> struct foo { int x; struct foo *next; }; #define CONST __attribute__((used, section("const_heap"))) // 段起始占位标记 char __const_heap_start CONST = 0; struct foo f CONST = { 1, 0 }; struct foo g CONST = { 2, &g }; // 段结束占位标记 char __const_heap_end CONST = 0; int main() { printf("f: %p, g: %p\n", &f, &g); printf("start: %p, end %p\n", &__const_heap_start, &__const_heap_end); // 示例:判断指针是否在段内 void *ptr = &f; if (ptr >= &__const_heap_start && ptr <= &__const_heap_end) { printf("ptr is in const_heap section\n"); } }
编译运行:
hickory% tcc const.c && ./a.out f: 0x7f9b12c00010, g: 0x7f9b12c00020 start: 0x7f9b12c00000, end 0x7f9b12c00030 ptr is in const_heap section
解决方案2:使用自定义链接脚本
编写一个链接脚本(比如custom.ld),显式定义段边界符号:
SECTIONS { .const_heap : { __start_const_heap = .; *(.const_heap) __stop_const_heap = .; } }
编译时指定链接脚本:
hickory% tcc const.c -Wl,-Tcustom.ld && ./a.out
这样就能让TCC生成你原本使用的__start_const_heap和__stop_const_heap符号,无需修改代码。
内容的提问来源于stack exchange,提问作者tekknolagi
相关产品推荐
相关产品推荐

