【发布时间】:2017-06-23 09:25:07
【问题描述】:
我正在尝试了解一些gcc 功能,例如__attribute__,更准确地说,是如何使用__attribute__((__section__("foo"))) 在特定内存位置分配数据/代码。
我的设置
align.c
#include <stdio.h>
//Align some ints
#define BYTES 16
#define __weird_thing __attribute__((__section__("weird.data")))
int __weird_thing *bootstrap;
int a __attribute__((aligned(BYTES))) = 1;
int b __attribute__((aligned(BYTES))) = 2;
int c = 3;
int d __attribute__((aligned(BYTES))) = 4;
int main( int argc, char *argv[])
{
extern a, b, c, d;
int *p = &a;
printf(" a = %p \n", &a);
printf(" sizof(a) = %d\n", sizeof(a));
printf("__alignof__ = %d\n", __alignof__(a));
printf(" p = %p \n\n", p);
printf(" b = %p \n", &b);
printf(" sizof(b) = %d\n", sizeof(b));
printf("__alignof__ = %d\n", __alignof__(b));
p = p + (BYTES / sizeof(int));
printf(" p = %p \n\n", p);
printf(" c = %p \n", &c);
printf(" sizof(c) = %d\n", sizeof(c));
printf("__alignof__ = %d\n", __alignof__(c));
p = p + sizeof(b) / sizeof(int) ;
printf(" p = %p \n\n", p);
long unsigned int alignment;
for(;(alignment=( (long unsigned int) p) & (BYTES << 1 )- 1 , printf("alignment = %p\n",alignment), alignment != 0 ) ; p++);
printf(" d = %p \n", &d);
printf(" sizof(d) = %d\n", sizeof(d));
printf("__alignof__ = %d\n", __alignof__(d));
printf(" p = %p \n\n", p);
}
包括/不可能.h
int imposible(void);
不可能的.c
#include<imposible.h>
extern unsigned long int base;
int imposible(void)
{
base++;
return (int) &base;
}
ld.lds
SECTIONS
{
. = 0x10000;
weird.data : { *(weird.data) }
base = .;
}
问题
每当我尝试链接时,它都会因未定义的引用而失败
dudarev@Test-Sandbox section $ gcc -c align.c -o align.o
dudarev@Test-Sandbox section $ gcc -c -I include/ imposible.c -o imposible.o
imposible.c: In function ‘imposible’:
imposible.c:6:9: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
return (int) &base;
^
dudarev@Test-Sandbox section $ ld -T ld.lds align.o imposible.o -o a.out
align.o: In function `main':
align.c:(.text+0x27): undefined reference to `printf'
align.c:(.text+0x3b): undefined reference to `printf'
align.c:(.text+0x4f): undefined reference to `printf'
align.c:(.text+0x65): undefined reference to `printf'
align.c:(.text+0x79): undefined reference to `printf'
align.o:align.c:(.text+0x8d): more undefined references to `printf' follow
据我所知,它没有找到 printf,这意味着 stdio 没有链接。
我在this stackoverflow 问题之后安装了glibc-static,并尝试了-lc 与ld 的切换,最终结果是
dudarev@Test-Sandbox section $ ld -lc -T ld.lds align.o imposible.o -o a.out
ld: cannot find -lc
我错过了什么?
提前致谢
【问题讨论】:
-
尝试使用详细标志
-v在同一个文件(而不是ld)上运行gcc,并查看所有传递给ld(或collect2)的标志。 -
同样不相关但
return (int) &base;。为什么? -
@AjayBrahmakshatriya,这是输出pastebin.com/3w8Y4b62
-
@AjayBrahmakshatriya,对于不相关的,如上所述,我正在学习,我正在尝试使用 base 检索节指针地址。
-
是什么让你认为将指针投射到
int会给你节指针(不管那是什么)?