gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

DS development > Question about multiple .h/.cpp files

#148779 - Jeremysr - Thu Jan 10, 2008 6:18 am

In the past with my DS homebrew projects that use multiple files and header files, I always had a main.h file that all my .c files included, and the main.h file had a whole bunch of defines and includes. I now realize that it's probably better to seperate all my .cpp files so they work without depending on a giant main.h file.

My problem is that I can't figure out how to make all my files "share" global variables. With my previous DS homebrew projects I just put something like "int x;" in a header file and all my files could access that variable (I actually had one .h file for each .c file, but it would just include main.h, have some function prototypes, and define global variables.) When I try to put "int x;" in a header file now, though, it gives me an error, saying:

asdf.o:/home/.../source/asdf.cpp:20: multiple definition of `x'
main.o:/home/.../source/main.cpp:5: first defined here

main.cpp includes asdf.h and asdf.cpp includes asdf.h also. And I do have the "#ifndef _asdf_h #define _asdf_h ... #endif" code surrounding my header files.

Anyone know what I'm doing wrong? (Or should I post code?)

#148780 - eKid - Thu Jan 10, 2008 6:23 am

you shouldn't have any actual variable definitions in header files, what i would do is define the 'int x;' in whatever source file is most relevant to it, then in the 'main.h' that everything includes i would add 'extern int x;', which lets you access that external variable in other source files.

#148781 - zeruda - Thu Jan 10, 2008 6:30 am

Just a note, when you do int x; what you are doing is not only naming a variable, but also allocating memory for that variable. Hence putting variable declarations in header files is a no no.

So as said in the header file just put extern int x; This names the variable but doesn't allocate memory. Then in any one .c file that includes that header put the int x; declaration. At this point memory is allocated and also all .c files that can see the header file will also see that extern int x; and will thus have access to it.

#148782 - Jeremysr - Thu Jan 10, 2008 6:35 am

Alright thanks for the quick replies. :D I got it working with extern.

(BTW I don't use the main.h anymore, I was just explaining what I used to use in the first paragraph... but it doesn't matter)