LNK2005 Linker Trouble
I am trying to convert my project into using multiple linked .cpp files (with accompanying header files), instead of one .cpp file with many headers. In other words, I am trying to turn this:
main.cpp
main.h
ddraw_tools.h
dsound_tools.h
dinput_tools.h
into this:
main.cpp
ddraw_tools.cpp
dsound_tools.cpp
dinput_tools.cpp
main.h
ddraw_tools.h
dsound_tools.h
dinput_tools.h
Each .cpp file must have access to functions and variables in all the other files, and I can''t figure out how to do this without getting LNK2005 errors ("already defined in _main.obj"). I have tried using this type of thing:
#ifndef __DDTOOLS_H__
#define __DDTOOLS_H__
//mystuff
#endif
But this doesn''t work. Any ideas?
Function prototypes can be defined many times over without worry. For each prototype have only one function defintion in the most relavent source file and as long as the source files can see the prototypes they can access the function. For variables put the extern keyword in front of them in the header file(s) and then in only one source file (the most relevant one) put the variable decleration exactly as you did in the header file except without the extern keyword. The extern keyword can be thought of as saying "even though this source file may never be able to directly see this variable''s definition until all the object files (each source file is compiled into an object file) are linked as one, I know it''s out there so everyhing''s OK" I guess it can be sorta thought of as a prototype for the variable...
The #ifdef directive, I have only found useful to block off class/struct redefinition. Of course, I haven''t delved very deep into the bowls of C++ so take that with a grain of salt.
This brings up a point I don''t understand. From what I understand if you put a #ifndef directive in it should skip all source code until #endif if whatever isn''t defined yet isn''t so it should only go through once. The 2nd time through the preporcessor should have ripped out the variable definitions out of the source file so how can the variables be defined in more than one obj file? I''m probably just missing something obvious....
The #ifdef directive, I have only found useful to block off class/struct redefinition. Of course, I haven''t delved very deep into the bowls of C++ so take that with a grain of salt.
This brings up a point I don''t understand. From what I understand if you put a #ifndef directive in it should skip all source code until #endif if whatever isn''t defined yet isn''t so it should only go through once. The 2nd time through the preporcessor should have ripped out the variable definitions out of the source file so how can the variables be defined in more than one obj file? I''m probably just missing something obvious....
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement