You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何手动计算ELF格式程序的.data段大小?为何结果与预期不符

手动计算gcc无优化编译程序的.data段大小可行性问题

我希望不使用readelf或其他工具,仅通过查看代码来手动计算经gcc无优化编译的程序中.data段的大小,是否可行?

测试程序代码

ex1.h

#include <stdint.h>
#include <inttypes.h>

#define FORMAT_STRING   "%s%" PRId64
#define MESSAGE         "The Oddonaci Number is: "

int64_t FastOddonacci(int32_t n);
int64_t LinearOddonacciHelper(int32_t n, int64_t current, int64_t first, int64_t second, int64_t third);

ex1.c

#include "ex1.h"
#include <stdio.h>

int32_t n = 40;
int32_t a = 3;

int main(int argc, char* argv[]) {
    printf(FORMAT_STRING, MESSAGE, FastOddonacci(n * a));
    return 0;
}

int64_t FastOddonacci(int32_t n) {
    if (n >= 1 && n <= 3) {
        return 1;
    }
    return LinearOddonacciHelper(n, 3, 1, 1, 1);
}

int64_t LinearOddonacciHelper(int32_t n, int64_t current, int64_t first, int64_t second, int64_t third) {
    if (n == current) {
        return third;
    }
    current += 1;
    return LinearOddonacciHelper(n, current, second, third, first+second+third);
}

疑问点

我理解.data段包含所有已初始化全局变量,此处应为n和a两个int32_t变量,共8字节;宏定义的字符串内容应归入.rodata段。但用readelf查看显示.data段大小为0x18(24字节),这是为什么?

二次测试:将n和a改为int64_t(并调整对应函数签名)后,readelf显示.data段大小为32字节,和预期的16字节差值恰好为8字节,但缺失的16字节来自哪里?看起来并非对齐导致。

内容的提问来源于stack exchange,提问作者Nicholas Humphrey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:20:33