10

I try to declare a global variable config:

//general.h

struct config_t {
    int num;
};

extern struct config_t config;  //The global variable

Then I define config variable in general.c:

//general.c
#include "general.h"

struct config_t config = {
    num = 5;
};

But, when I try to use the global variable 'config' in my main function, I get the error:

undefined reference to `config':

Main program:

//main.c
#include "general.h"

main() {
    config.num = 10;
}

Why is it?

5
  • Do you get that error during compilation or during linking? Commented Apr 29, 2014 at 14:21
  • @SergeyL. - During linking Commented Apr 29, 2014 at 14:22
  • To avoid linker errors, always use header guards #ifndef MY_HEADER_H #define MY_HEADER_H /* contents */ #endif. You must have this in every header file you ever make. Commented Apr 29, 2014 at 14:27
  • And like sergey answered (which is the pertinent point in this case), don't forget to link all your code together. Commented Apr 29, 2014 at 14:28
  • 1
    @Lundin A header guard won't help you outside a compilation unit. So "undefined reference" and "redefinition of" from ld are mostly unaffected by it. Commented Nov 1, 2016 at 19:28

1 Answer 1

11

This looks like a linker error. You need to make sure you link your executable properly:

cc -c general.c
cc -c main.c
cc general.o main.o
./a.out

The -c flag instructs your compiler not to link yet. In order to link the object file containing config needs to be available at that moment.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.