我希望gcc优化掉未使用的函数指针 . 即从最终的可执行文件中完全删除代码 . 到目前为止,我无法做到这一点 .

这是更新的代码:

#include <stdio.h>

struct inner {
    void (*fun)(void); 
    void (*fun2)(void); 
}; 

struct inner2 {
    void (*fun)(void); 
}; 

struct foo {
    struct inner in; 
    struct inner2 in2; 
}; 

void lessfun(){
    printf("lessfun\n");
}

void morefun(){
    printf("morefun\n"); 
}

const struct foo inst = {
    { .fun = lessfun, .fun2 = morefun }, 
    { .fun = lessfun }
}; 

void test(struct foo *f){
    f->in.fun(); 
}

int main(int argc, char *argv){
    struct inner2 in = inst.in2;  
    inst.in.fun(); 
    inst.in.fun2(); 
    in.fun(); 

    /////////////// alt1: nm out | grep morefun -> found
    test(&inst); 
    ///////////////

    /////////////// alt2: nm out | grep morefun -> not found
    struct inner in; 
    struct inner in2 = inst.in; 
    in = in2; 
    test(&in); 
    ///////////////
}

编译器标志:-Os -fdata-sections -Wl, - relax, - gc-sections -ffunction-sections链接标志:-flto -Os -fdata-sections -Wl, - relax, - gc-sections

编译器:arm-none-eabi-gcc

这里编译器将method1和method2都包含在最终程序中,即使它们从未使用过 . 这项任务似乎可以实现这一目标 . 但是如果它们从未被调用过,那么将代码完全删除到method1和method2会更好 . 这显然是因为从技术上讲,函数实际上是在赋值中引用的,但由于赋值中的变量永远不是用户,因此仍然可以确定永远不会调用该方法 .

我需要以某种方式声明它const吗?怎么样?

如何让gcc删除未使用的函数?

编辑:我能够让你按照上面的说法工作 . 但它只有在我不复制任何结构成员的情况下才有效 . 如果直接复制并传递给函数,则编译器无法优化未使用的函数 . 我现在60%肯定这是某种优化器错误 .

EDIT2:您甚至可能无法重现该错误 . 但这是创建它的场景 .

struct mydev dev;  
struct dev_spi spi; 
struct dev_spi sp2 = board.spi0; 
sp2.writereadbyte(0); 
spi = sp2; 
//test(&cpu.spi0); 

// using only this call results in correct optimization
// many unused methods pointed to by members of "board" var are gone.
mydev_init(&dev, &spi); 

// using this version breaks optimization
// all methods referenced by "board" struct are included in final program
mydev_init(&dev, &sp2); 

// this one breaks optimization as well
// same as above. 
mydev_init(&dev, &board.spi0); 

// there is no difference other than one passes variable directly to the init function
// and the other uses a temp variable.