Reputation: 942
I am trying to define a global pointer to a struct
- font - so I can use it whenever I need it along my project.
When I compile, I get this error initializer element is not constant
at line Font_t* font = load_font("ubuntu");
of Font.c
.
Font.h:
#ifndef __FONT_H
#define __FONT_H
#include "Bitmap.h"
#include "Utilities.h"
/// Represents a Font
typedef struct {
int letterSpacing;
// symbols
Bitmap_t* space;
(...)
Bitmap_t* y;
Bitmap_t* z;
} Font_t;
extern Font_t* font;
/**
* @brief Loads a font from disk
*
* @param filename name of the font to load
*/
Font_t* load_font(char const* fontName);
Font.c:
#include "Font.h"
#include "stdio.h"
#include "Utilities.h"
#include "video_gr.h"
Font_t* font = load_font("ubuntu");
Font_t* load_font(char const* fontName) {
Font_t* font = (Font_t*) malloc(sizeof(Font_t));
font->letterSpacing = 1;
char path[200];
strcpy(path, fontsPath);
strcat(path, fontName);
char tempPath[200];
strcpy(tempPath, path); strcat(tempPath, "/space.bmp"); font->space = load_bitmap(tempPath);
(...)
strcpy(tempPath, path); strcat(tempPath, "/y.bmp"); font->y = load_bitmap(tempPath);
strcpy(tempPath, path); strcat(tempPath, "/z.bmp"); font->z = load_bitmap(tempPath);
return font;
}
Upvotes: 1
Views: 1878
Reputation: 23031
You can do something like this to keep the initialization of your font in the font module.
Header:
// extern Font_t* font; // delete this
Font_t* get_default_font(); // use a function instead
Source:
Font_t* g_default_font = NULL;
Font_t* get_default_font() {
if(!font) {
g_default_font = load_font("ubuntu");
}
return g_default_font;
}
Upvotes: 2
Reputation: 206646
Font_t* font = load_font("ubuntu");
You cannot do that. You are not allowed to call functions this way in global scope. You will need to split the declaration and the initialization.
At global scope:
Font_t* font;
On first use, inside main:
font = load_font("ubuntu");
Upvotes: 3
Reputation: 11448
You cannot initialize a global variable with something which is not a constant value. Place this line:
font = load_font("ubuntu");
In your code, before any other code that tries to use font
.
And leave as global declaration only this line:
Font_t* font = NULL;
Upvotes: 1
Reputation: 2568
Are you using this outside all functions
Font_t* font = load_font("ubuntu");
if so ,I don't think you will be able to do so ??
Upvotes: 0