c - 尝试声明全局结构时,初始值设定项元素不是常量

标签 c

我目前是一名 Java 程序员,正在为一个类使用 C 语言做一些工作,我一直在努力解决两者之间的差异。目前,我正在尝试使用编译器 Hook 添加功能,以计算在正在执行的程序的每个函数中花费的时间。我为此苦苦挣扎的是,我的解决方案是使用堆栈,而且我无法实例化堆栈(如果这甚至是正确的词?)堆栈,因为我无法添加 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 堆栈的行。我该如何解决这个错误,或者重构我的代码来防止这个问题?

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

最佳答案

在 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

关于c - 尝试声明全局结构时,初始值设定项元素不是常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52733459/

相关文章:

c - 如何解决这个编译警告? (格式说明符问题)

c++ - 在 C++ 中使用 C 特性是不好的做法吗?

c - 假设 pid_t 始终是 int 类型(如标准中所定义)是否安全?

c - 为什么条件运算符是右结合的?

c - 从 C 中的函数返回矩阵

c++ - C 语法 - 错误 C2143 : syntax error : missing ')' before '*'

c - 整型常量的默认大小

c - "dereferencing"这个词是从哪里来的?

在我的 DCT/IDCT 代码中找不到错误

c - C : Merge Sort implementation - memory allocation 错误