c - 为什么不同类型的符号占用相同的长度?

标签 c object-files nm

我在 x64 机器上使用 cygwin GCC 编译了以下代码:

gcc main.c -o main

(main.c)

long long mango = 13; // I also tried `char`, `short`, `int`
long melon = 2001;

void main()
{

}

然后我用 nm 转储符号值:

./main:0000000100402010 D mango
./main:0000000100402018 D melon

据我了解,符号的值仅意味着它的地址。因此,mango 的地址是 100402010melon 的地址为 100402018。所以mango应该占用8个字节。

我尝试了 mango 的其他类型,例如 charintshort。始终占用8个字节。

为什么尺寸没有改变?

添加1

感谢评论。

我刚刚尝试了以下代码:

typedef struct{
    char a1;
    char a2;
    char a3;
    char a4;
    char a5;
} MyStruct;

MyStruct MyObj1={1,2,3,4,5};

MyStruct MyObj2={1,2,3,4,5};

long long mango = 13;
long melon = 2001;

void main()
{

}

这一次,nm 向我展示了这个:

./main:0000000100402020 D mango
./main:0000000100402028 D melon
./main:0000000100402010 D MyObj1
./main:0000000100402015 D MyObj2

MyObj1MyObj2 间隔 5 个字节。所以填充确实是由编译器决定的。

最佳答案

来自 GNU nm binary utilities: nm page :

The symbol value, in the radix selected by options (see below), or hexadecimal by default. The symbol type. At least the following types are used; others are, as well, depending on the object file format. If lowercase, the symbol is usually local; if uppercase, the symbol is global (external). There are however a few lowercase symbols that are shown for special global symbols (u, v and w). Depending on pragma settings and default alignment boundaries, the distance between successive symbol address may be the exact value of the number of bytes for that symbol type, or it may include padding, which increases the apparent sizeof the symbol.

A

    The symbol’s value is absolute, and will not be changed by further linking.
B
...

IMO 在 nm 说法中使用单词value是不幸的,因为在这种情况下value用于描述符号的地址。符号(值)的地址不会改变。但在正常的 C 语言中,符号的确实会改变,例如:

int i = 0; // the address for symbol i will remain constant
i = 10;    // but the value of the symbol i can change. 

关于地址大小,64 位构建的任何符号地址的大小始终为 8 字节,而 32 位构建的任何符号的地址大小均为 4 字节。这些大小不会改变,也不会受到为分配给它们的符号分配的影响。

关于各种符号之间在内存空间中出现的距离,这个距离同时受到符号类型的影响,它是如何 aligned 沿着实现边界,并且正如您所指出的,编译器:“因此确实由编译器来决定填充。” 取决于 pragma设置和默认对齐边界, padding 可能会导致连续符号的地址距离大于仅由typetypes的组合sizeof值引起的距离code> 定义特定符号。 (对于 charstruct 类型符号来说非常常见)。

关于c - 为什么不同类型的符号占用相同的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50044868/

相关文章:

c++ - 在二进制数据文件的头部放什么

c - 如何检查.so 中定义的宏?我会使用 nm 来检查功能,有没有办法对宏做同样的事情?

c++ - 按偏移量查找成员

c - 指针导致C程序崩溃

c - 使用 C 的 do-while 循环

c++ - Visual Studio LNK2019 中的链接对象文件

linux - 是否可以从库中获取函数的签名?

html - C CGI 中的 getenv(QUERY_STRING)

c - linux .s 文件的大小大于 .o 文件