[英]Initializer element is not constant when trying to declare a global struct
我目前是一名Java程序員,為一個類在C中做一些工作,而我一直在為兩者之間的差異而苦苦掙扎。 當前,我正在嘗試使用編譯器掛鈎添加功能,以計算所執行程序的每個功能所花費的時間。 我為此所做的努力是,我的解決方案是使用堆棧,而我無法實例化(如果使用的話甚至合適嗎?)堆棧,因為我無法添加主方法或此類方法來創建它在一開始。 現在是我的代碼:
#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語言中,在文件或全局范圍內初始化變量時無法調用函數。
您應該調用malloc
為您分配一些內存,如下所示:
static stack_t* entry_times = NULL;
entry_times = (stack_t*)malloc(500 * sizeof(stack_t));
這將為您提供500個stack_t
實例。
當您不再需要內存時,您需要free
。
編輯:
這是我為您解決的問題的解決方案-不太漂亮,但是如果您僅具有這兩個功能,則將受到很大限制...
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "mystack.h"
static stack_t* entry_times=NULL;
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){
if (entry_times == NULL) {
entry_times = (stack_t *)malloc(500 * sizeof(stack_t));
}
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++;
if (entry_times != NULL) {
free(entry_times);
entry_times = NULL;
}
printf("Time in Function: %d\n", difference);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.