Home > Backend Development > C++ > Why Does My C Code Get an 'Undefined Reference to Static Variable' Linker Error?

Why Does My C Code Get an 'Undefined Reference to Static Variable' Linker Error?

Patricia Arquette
Release: 2024-12-19 03:18:12
Original
176 people have browsed it

Why Does My C   Code Get an

Undefined Reference to Static Variable: Resolving Link Errors

When compiling C code, you may encounter a "Undefined symbols" error when referencing a static variable defined in a header file. This error occurs because the linker cannot find the definition of the static variable during linking.

In the example provided, the header file Log.h declares a static string member theString. However, the definition of this static variable is missing from the Log.cpp file. To resolve this issue, follow these steps:

  1. Define the Static Variable in the CPP File:

    • Add the definition of the static variable to the CPP file (Log.cpp).
    #include "Log.h"
    #include <iostream>
    
    // Define the static variable here
    string Log::theString;
    
    void Log::method(string arg) {
        theString = "hola";
        cout << theString << endl;
    }
    Copy after login
  2. Remove Unnecessary Namespace Declaration:

    • Remove using namespace std; from the header file (Log.h). This is considered bad practice as it pollutes the global namespace.

By making these changes, the linker will be able to find the definition of the static variable during linking, resolving the "Undefined symbols" error.

The above is the detailed content of Why Does My C Code Get an 'Undefined Reference to Static Variable' Linker Error?. 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