Home > Backend Development > C++ > Undefined Reference to Static Member in C : How to Resolve Compilation Issues?

Undefined Reference to Static Member in C : How to Resolve Compilation Issues?

Susan Sarandon
Release: 2024-12-28 20:40:18
Original
774 people have browsed it

Undefined Reference to Static Member in C  : How to Resolve Compilation Issues?

Undefined Reference to a Static Member: Resolving Compilation Issues

When working with static members in C , particularly while using a cross compiler, you may encounter the error "undefined reference to a static member." This error occurs due to the lack of a definition for a static member variable in a source file. To resolve this issue, follow these steps:

Understanding the Issue

In your example, you have defined a static member variable _frequency within the class WindowsTimer. However, you have not defined its actual data in a separate source file (.cpp file). This is the root cause of the compilation error.

Solution: Defining Static Members

To fix the error, define the static member variable in a separate source file, typically a .cpp file. For example:

// WindowsTimer.cpp

LARGE_INTEGER WindowsTimer::_frequency;
Copy after login

This definition allocates memory for the static variable and allows the compiler to reference it during the linking stage.

Why External Definition is Necessary

When working with static members, it's important to understand that their definition must be external to the class declaration. This is because the compiler requires the full definition of a static member before generating the code and linking the object files.

Avoid Placing Definitions in Header Files

While it's tempting to define static members inside header files (.h files) for ease of access, it's not a good practice. Multiple inclusions of the header file can lead to multiple definitions of the static variable, resulting in linker errors or undefined behavior.

The above is the detailed content of Undefined Reference to Static Member in C : How to Resolve Compilation Issues?. 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