c - 尝试声明全局结构时,初始值设定项元素不是常量
问题描述
我目前是一名 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 堆栈的行。如何解决此错误,或重构我的代码以防止此问题?
如果这是一个重复的主题,我很抱歉,我已经进行了大量的搜索,我怀疑我根本不知道要实际搜索什么来找到我正在寻找的信息。
解决方案
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# - 我的代码的 for 循环出错 - 错误消息指出“输入字符串格式不正确”
- sass - 无法在 Shopify 中打印液体变量值
- javascript - 如何利用 event.target 将 JS 函数合并为一个函数?
- python-3.x - 在用户创建的列表中删除“和”之后的“,”需要帮助
- php - 单击列表中的一项以显示新页面
- sql-server - 使用 Windows 身份验证或 SQL 身份验证链接到 Postgresql 时的奇怪设置
- javascript - 使用 React Leaflet 更改地图位置
- windows - 哪种 Windows 10 驱动程序模型适用于实现 IP 链路层?
- python - Python 用 if/else 附加一个字符串?
- css - IONIC 4 ion-content 内滚动滚动条颜色/主题 w/ Electron 应用程序