I try add global variable in my buttons.c
file, but have a error - initializer element is not constant
. Example headers.h
file
struct MainStruct {
GtkEntryBuffer *buffer;
GtkWidget *entry;
GtkWidget *label;
};
extern struct MainStruct *p;
extern const char *text_entry;
void lower_button_clicked(GtkWidget *lowerbutton);
and when file main.c calls file buttons.c, I cannot define the variable text_entry
. What am I doing wrong?
buttons.c
#include <gtk/gtk.h>
#include "headers.h"
const char *text_entry = gtk_entry_buffer_get_text(p -> buffer); // is not constant, why?
void lower_button_clicked(GtkWidget *lowerbutton)
{
printf("%s\n", text_entry);
}
I saw a lot of similar questions that talk about static, but
static const char *text_entry = gtk_entry_buffer_get_text(p -> buffer);
not working. How do I define this variable to be global? to avoid duplication in similar functions
From the C Standard (6.7.9 Initialization)
4 All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.
And in this declaration
const char *text_entry = gtk_entry_buffer_get_text(p -> buffer);
the initializer is not a constant expression. So the compiler issues an error.
Also pay attention to that these declarations
extern const char *text_entry;
and that follows it
static const char *text_entry = /*...*/;
contradict each other. The first declaration declares the variable text_entry as having external linkage while the second declaration declares the variable as having internal linkage.