+ 2
Template instantiation with different project | Base derived class
Here code below: https://www.sololearn.com/en/compiler-playground/c4klNA8CnhM6 This code compiles fine and no issue. Issue arises when baseT class and derivedT class are part of different project. Due to this separation, setSlot method which is templated will not be defined by compiler as different project has this method usage. Now when derived class related project is build, it fails to find this method while linking with base class project dll. How to avoid this issue? https://sololearn.com/compiler-playground/c4klNA8CnhM6/?ref=app
5 Antworten
+ 3
It sounds like one of the projects is missing the template definition. Template definitions are typically placed in header files. Templates are processed by the compiler, not the linker. (The linker is what links references to dlls). Both projects should be including the template header file wherever the template is used.
+ 3
Yes, that situation would cause redefinition error. A common way to avoid redefinition is to use preprocessor directives in each header file that check for prior definition of a unique symbol defined in the header. It looks like this:
#ifndef HEADER_FILE_NAME
#define HEADER_FILE_NAME
// Entire header file content
#endif // HEADER_FILE_NAME
Some C++ compilers have a convenient #pragma option that handles this automatically if you place it at the beginning of every header file:
#pragma once
+ 1
Sounds good Brian
I have a query about redefiniton of function.
Suppose, I have a header file a.h in solution A which has function defined in header itself.
Now, another solution B has two files b.h and c.h and both of these includes a.h. . does this not mean solution B has two definition of header function (one via b.h and other via c.h ) causing redefinition error?
0
Hi Brian
I observed very different outcome.
I have four files like Header1.h , Header2.h , Common.h and Source.cpp
All three header files have #pragma once defined at the start of the header file
Header1.h and Header2.h includes Common.h
Source.cpp includes both Header1.h and Header2.h
Common.h has function defined as void add() {}
Compiling this solution works and builds successfully.
To my surprise, It still compiles successfully even though I remove the pragma statements. Why it works without pragma protection?
0
Scenario 2:
I have four files like Common.h , Source.cpp and Source2.cpp
Common.h file has #pragma once defined at the start of the header file and has one function defined as void add() {}
Common.h is included in Source.cpp and Source2.cpp
This set up fails to compile as Add function is defined in two units Source.obj and Source2.obj