首页 > 解决方案 > 尝试声明全局结构时,初始值设定项元素不是常量

问题描述

我目前是一名 Java 程序员,在 C 语言中为一个类做一些工作,我一直在努力解决两者之间的差异。目前,我正在尝试使用编译器挂钩添加功能,以计算在正在执行的程序的每个函数中花费的时间。我对此的斗争是我的解决方案是使用堆栈,而我无法实例化(如果这甚至是正确的词?)堆栈,因为我无法添加 main 方法或类似的东西来创建一开始。这是我现在的代码:

#include <stdio.h>
#include <time.h>
#include "mystack.h"

static stack_t* entry_times=create_stack(500);
static unsigned int count_entered=0;
static unsigned int count_completed=0;


__attribute__((no_instrument_function))
void __cyg_profile_func_enter(void *this_fn, void *call_site){
    count_entered++;
    time_t start_time;
    time(&start_time);
    stack_enqueue(entry_times, start_time);
    printf("Total Functions Entered: %d\n", count_entered);

}

__attribute__((no_instrument_function))
void __cyg_profile_func_exit(void *this_fn, void *call_site){

    time_t end_time;
    time(&end_time);
    time_t start_time = stack_dequeue(entry_times);
    double difference = difftime(end_time, start_time);
    count_completed++;
    printf("Time in Function: %d\n", difference);

}

现在,当我尝试编译此代码时,我收到一个“初始化元素不是常量”错误指向我创建 entry_times 堆栈的行。如何解决此错误,或重构我的代码以防止此问题?

如果这是一个重复的主题,我很抱歉,我已经进行了大量的搜索,我怀疑我根本不知道要实际搜索什么来找到我正在寻找的信息。

标签: c

解决方案


John Zwinck 的链接中解释了您收到错误的原因,但如何为您解决它取决于您。您可以创建为您进行初始化的构造函数,例如

static stack_t* entry_times;
__attribute__((constructor))
void my_init(){
    entry_times=create_stack(500);
}

或者你可以围绕它创建一个包装函数

stack_t* my_entry_times(){
    static stack_t* entry_times;
    if (!entry_times) {
        entry_times=create_stack(500);
    }
    return entry_times;
}

并在代码中使用my_entry_times()而不是entry_times


推荐阅读