I have global SDL_Renderer* and it becomes within function calls.
I have reduced my program to this MWE and the issue is still reprocudeable. In GDB, you can switch between between the function and main stack frames and see the variable as pointing to 2 different locations.
MWE source:
#include <stdio.h>
#include <SDL2/SDL.h>
SDL_Window *gWindow;
SDL_Renderer *gRenderer;
void func() {
SDL_Rect rect = { 100, 100, 100, 100 };
SDL_SetRenderDrawColor(gRenderer, 200, 100, 50, 255);
SDL_RenderClear(gRenderer);
SDL_SetRenderDrawColor(gRenderer, 50, 100, 200, 255);
SDL_RenderFillRect(gRenderer, &rect);
SDL_RenderPresent(gRenderer);
}
int main(int argc, char *argv[]) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *gWindow = SDL_CreateWindow(
"Float",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
300, 300,
SDL_WINDOW_SHOWN
);
SDL_Renderer *gRenderer = SDL_CreateRenderer(
gWindow,
-1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC
);
SDL_SetRenderDrawBlendMode(gRenderer, SDL_BLENDMODE_BLEND);
func();
SDL_DestroyWindow(gWindow);
SDL_DestroyRenderer(gRenderer);
return 0;
}
GDB output:
Reading symbols from ./a.out...
(gdb) break 8
Breakpoint 1 at 0x11f0: file test.c, line 8.
(gdb) run
Starting program: /home/oh/code/vania/scrape/a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/usr/lib/libthread_db.so.1".
[New Thread 0x7ffff531f700 (LWP 16701)]
Thread 1 "a.out" hit Breakpoint 1, func () at test.c:8
8 SDL_Rect rect = { 100, 100, 100, 100 };
(gdb) print gRenderer
$1 = (SDL_Renderer *) 0x0
(gdb) frame 1
#1 0x0000555555555318 in main (argc=1, argv=0x7fffffffe7b8) at test.c:31
31 func();
(gdb) print gRenderer
$2 = (SDL_Renderer *) 0x555555763f40
(gdb) continue
Continuing.
[Thread 0x7ffff531f700 (LWP 16701) exited]
[Inferior 1 (process 16697) exited normally]
(gdb) quit
If my understanding of global variables is correct, the gRenderer should point to the same variable in all scopes. Forgive me if I just misunderstand global variables, if that is the issue, where am I misunderstanding?
You've declared new local variable with the same name but with reduced scope; it is called shadowing. Don't declare new variable if you don't want that, e.g.:
gRenderer = SDL_CreateRenderer(...);