全局SDL_Renderer *在函数调用上发生变化

时间:2019-07-09 03:32:23

标签: c gdb sdl-2

我有全局SDL_Renderer *,它可以在函数调用中使用。

我已将程序简化为该MWE,但该问题仍然可以解决。 在GDB中,您可以在函数框架和主堆栈框架之间切换,并看到变量指向2个不同的位置。

MWE来源:

#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输出:

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/scrap/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

如果我对全局变量的理解是正确的,则gRenderer应该在所有范围内都指向相同的变量。 如果我只是误解了全局变量,请原谅我,如果这是问题,我在哪里误解了?

1 个答案:

答案 0 :(得分:1)

您已经声明了具有相同名称但范围缩小的新局部变量;它称为shadowing。如果您不想这么做,请不要声明新变量,例如:

gRenderer = SDL_CreateRenderer(...);