我在 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
的地址是 100402010
。 melon
的地址为 100402018
。所以mango
应该占用8个字节。
我尝试了 mango
的其他类型,例如 char
、int
、short
。始终占用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
MyObj1
和 MyObj2
间隔 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 symboltype
, 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 可能会导致连续符号的地址距离大于仅由type
或types
的组合sizeof值引起的距离code> 定义特定符号。 (对于 char
和 struct
类型符号来说非常常见)。
关于c - 为什么不同类型的符号占用相同的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50044868/