Home > Backend Development > C++ > Why Do I Get Undefined References When Separating Templated C Class Implementations into .hpp and .cpp Files?

Why Do I Get Undefined References When Separating Templated C Class Implementations into .hpp and .cpp Files?

Barbara Streisand
Release: 2024-12-28 05:48:15
Original
798 people have browsed it

Why Do I Get Undefined References When Separating Templated C   Class Implementations into .hpp and .cpp Files?

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();
};
Copy after login

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;
}
Copy after login

main.cpp:

#include "stack.hpp"

int main() {
    stack<int> s;

    return 0;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template