I am trying to separate drawing (drawing.c)
to the screen from the creation of a window and renderer (initialize.c)
. I want them both in different source-files. The drawing code runs and is executed, but the graphics are not updated.
If I put the code from the drawing file inside the create window and rendering file, it works. The color in the window is now red.
main.c - The main file
SDL_Window *window;
SDL_Renderer *renderer;
int main()
{
initialize(window, renderer);
draw(renderer);
SDL_Dealy(5000);
SDL_Quit();
}
initialize.c - Create window and renderer
void initialize(SDL_Window *window, SDL_Renderer *renderer)
{
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("Title",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
640, 480, 0);
renderer = SDL_CreateRenderer(window, -1, 0);
}
draw.c - Draw graphics to window
void draw(SDL_Renderer *renderer)
{
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}
When I run the code the window display is black. It is supposed to be filled with red. I get no error messages when I run the code. The new color graphics are never rendered visible.
I can't see how it could have worked in single file unless actual code is different from presented in question. Look at your initialise function:
void initialize(SDL_Window *window, SDL_Renderer *renderer)
{
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("Title",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
640, 480, 0);
renderer = SDL_CreateRenderer(window, -1, 0);
}
When you call it from main
as initialize(window, renderer);
, it gets values of global window
and renderer
. Then it assigns new window/renderer to its local variables, which gets lost when function returns - no global variable is modified after this. Then you call draw(renderer);
with the same global not-assigned renderer
(NULL) - no way it would work as you expect.
Basically function can't modify anything passed as its arguments because it gets copy of passed values. Correct version would look like this:
void initialize(SDL_Window **window, SDL_Renderer **renderer)
{
SDL_Init(SDL_INIT_WINDOW);
*window = SDL_CreateWindow("Title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
*renderer = SDL_CreateRenderer(window, -1, 0);
}
// ...
// in file with main func
SDL_Window *window;
SDL_Renderer *renderer;
void initialize(SDL_Window **window, SDL_Renderer **renderer);
void draw(SDL_Renderer *renderer);
int main()
{
// ...
initialize(&window, &renderer);
draw(renderer);
// ...
}
This is the same way how SDL_CreateWindowAndRenderer operates.
Another thing is that you can't expect draw-and-delay to be correctly displayed; it may work on your configuration of OS/window manager/settings/luck but not others. Refresh loop is essential.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.