- If you try to define templates in multiple files, it is likely that you will
come across a linker error in Visual C++.
The error might be something like the following:
main.obj : error LNK2001: unresolved external symbol "public: __thiscall LinkedList::~LinkedList(void)" (??1?$LinkedList@H@@QAE@XZ)
- To get rid of this error, you need to tell the Visual C++ compiler
in what order to compile the files and only to compile them once.
- You do this by using some preprocessor directives, which are
instructions to the compiler.
- All preprocessor directives begin with a # sign.
- You have already been using one preprocessing directive: #include.
- To get rid of the linker error when using templates, you can use three new
- The general form of #ifndef is:
- This means that if name is currently undefined, then
compile all the code up to the matching #endif line.
- Using the following format in a file, the code up to the
#endif will only be compiled once.
If the compiler encounters the file again during the compilation,
name will be already defined and all code up
to and including the #endif will be ignored.
- Note: name might be something like "LINKEDLIST_H".
The tradition for identifier names is that they should match the file name.
The period character ('.') is not valid for identifiers, so it is replaced
by the underscore ('_') character.
- Putting it all together, the general format for all the files should be as
for each .h file, add-in
for each .cpp file, add in
- Again, this tells the Visual C++ compiler in
what order to compile the files and compiles them only once.