Splitting Templated C Classes into .hpp/.cpp Files
Problem:
Compiling a C template class split between .hpp and .cpp files results in undefined reference errors for template member functions.
Code:
stack.hpp:
template <typename Type> class stack { public: stack(); ~stack(); };
stack.cpp:
#include <iostream> #include "stack.hpp" template <typename Type> stack<Type>::stack() { std::cerr << "Hello, stack " << this << "!" << std::endl; } template <typename Type> stack<Type>::~stack() { std::cerr << "Goodbye, stack " << this << "." << std::endl; }
main.cpp:
#include "stack.hpp" int main() { stack<int> s; return 0; }
Answer:
Explanation:
It is not feasible to split the implementation of a templated class into separate .cpp files for compilation. The header files are only preprocessed and do not contain the actual code.
Compilation Process:
When compiling, the preprocessed header code is combined with the .cpp file. However, for template classes, the compiler needs information about the template data type to generate the memory layout and method definitions.
Separate cpp File Issue:
Moving the method definitions to a separate cpp file without instantiating the template class in the header file will not generate the necessary object file information. Therefore, the linker cannot find the symbols, leading to undefined reference errors.
Alternative Approach:
To separate interface from implementation, consider separating data structures from algorithms. Template classes should represent data structures only. Algorithms can be implemented in separate non-templatized class libraries that interact with or utilize the template classes. This approach allows for the hiding of valuable implementation details.
The above is the detailed content of Why Do I Get Undefined References When Separating Templated C Class Implementations into .hpp and .cpp Files?. For more information, please follow other related articles on the PHP Chinese website!