Using TTF_Font with external linkage


#1

Hey guys. New SDL user here. I’m working on a project, and I want to move the initializations to a separate CPP file than my game loop. It started out pretty good, I was able to move the SDL_Init function, the TTF_Init function, and the Surface creation to another cpp file, and declare them extern in the header. That worked fine. But when I move this function:

// In the header file:
extern TTF_Font* Font

// TTF_Font initialized globally in the 2nd CPP file:
TTF_Font* Font = TTF_OpenFont("/usr/share/fonts/truetype/freefont/FreeSans.ttf", 42);

// inside of a function inside the 2nd CPP file:
if (!Font)
{
std::cerr << "TTF_OpenFont() Failed: " << TTF_GetError();
TTF_Quit();
SDL_Quit();
return 1;
}

TTF_OpenFont failed is the error I get. I’ve been going nuts trying to figure out why. It works fine when that code is in main.cpp, so it’s not permission or filepath issue.

Any ideas would be appreciated. Thanks.


#2

It’s hard to tell with this limited sample of code, but there are things to be careful about here.

Depending on global variable initialization order is a bad idea. You’d have to dig through the standard to figure it out, but to be safe, you should initialize your globals to a constant, e.g. nullptr for pointers. In your main(), you can explicitly control initialization order. You’ll want to initialize both SDL and SDL_ttf before the call to TTF_OpenFont().


#3

Thanks man.

You were right. It was the the global definition/initialization that was screwing it up.

I instead declared it globally in the 2nd cpp file, and defined it inside of a function in the 2nd cpp file, which was called from the main function:

// In the header file:
extern TTF_Font* Font

// TTF_Font declared globally in the 2nd CPP file:
TTF_Font* Font;

// inside of a function inside the 2nd CPP file:
TTF_Font* Font = TTF_OpenFont("/usr/share/fonts/truetype/freefont/FreeSans.ttf", 42);
if (!Font)
{
std::cerr << "TTF_OpenFont() Failed: " << TTF_GetError();
TTF_Quit();
SDL_Quit();
return 1;
}