Home > Backend Development > C++ > Why Am I Getting a Static Variable Link Error in C ?

Why Am I Getting a Static Variable Link Error in C ?

Patricia Arquette
Release: 2024-12-31 08:02:09
Original
408 people have browsed it

Why Am I Getting a Static Variable Link Error in C  ?

Static Variable Link Error [Duplicate]

In C programming, a link error can occur when a static variable is declared but not defined in the code. This error indicates that the linker cannot find the definition of the static variable during the linking phase.

In the given code, the class Log has a static variable theString declared in the header file Log.h, but it is not defined in the implementation file Log.cpp. To resolve the link error, the static variable must be defined in the implementation file.

The corrected code in Log.cpp should be:

#include "Log.h"
#include <ostream>

string Log::theString;  // Define the static variable here

void Log::method(string arg) {
    theString = "hola";
    cout << theString << endl;
}
Copy after login

Additionally, it is recommended to remove the using namespace std; line from the header file. This practice prevents polluting the global namespace with std symbols, which can lead to naming conflicts and potential errors.

The above is the detailed content of Why Am I Getting a Static Variable Link Error in C ?. 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