cgcccompiler-errorslinker-errors

Undefined Reference? But I've already implemented the function


display.h

#ifndef PRO_DISPLAY_H
#define PRO_DISPLAY_H

/** Initializes the display **/
int pro_display_init(void);

#endif /* PRO_DISPLAY_H */

display.c

#include "main.h"

static int height_ = 300;
static int width_ = 300;
static int bpp_ = 16;

static SDL_Surface* screen_ = NULL;

int pro_display_init(void)
{
    screen_ = SDL_SetVideoMode(width_, height_, bpp_, SDL_HWSURFACE|SDL_DOUBLEBUF);
    if (!screen_)
    {
        pro_sdl_error("Video initialization failed.");
        return 0;
    }

    return 1;
}

main.h

#ifndef PRO_MAIN_H
#define PRO_MAIN_H

// standard headers
#include <stdlib.h>
#include <stdlib.h>

// conditional headers
#if defined(WIN32) || defined(_WIN32)
#include <windows.h>
#endif

// our own headers
#include "scripter.h"
#include "ttf_util.h"
#include "events.h"
#include "display.h"

// some macros
#define pro_error(...) fprintf(stderr, __VA_ARGS__)
#define pro_sdl_error(x) fprintf(stderr, "%s. \n=> %s\n", x, SDL_GetError())
#define pro_ttf_error(x) fprintf(stderr, "%s. \n=> %s\n", x, TTF_GetError())

#endif /* PRO_MAIN_H */

** main.c**

#include "main.h"

int main(int argc, char* argv[])
{
    pro_display_init();
    return 0;
}

The Error:

main.c|5|undefined reference to `pro_display_init()'|

Checked the build process. Made sure I was adding "display.c" to gcc's input files. I'm at my wit's end. Why the error?


Solution

  • display.c and main.c are compiled into their own "translation unit". What happens is that when trying to resolve symbols name (i.e. looking for pro_display_init), the C compiler thinks it's compiling a standalone .c unit. The proper way to go is to compile them separately and then link them, e.g.

    gcc -c display.c # creates display.o
    gcc main.c display.o # compiles main.o and then link with display.o
    

    Of course, you'll be creating/reusing a Makefile soon that lets you define rules for all this.