C ++ unresolved external character

Hi iam begginer in C ++ I have a class with static methods and I cannot access them, this causes an error

1>------ Build started: Project: CPractice, Configuration: Debug Win32 ------ 1> Source.cpp 1>Source.obj : error LNK2001: unresolved external symbol "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > CPractice::name" ( ?name@CPractice @@ 0V?$basic_string@DU ?$char_traits@D @ std@ @ V?$allocator@D @ 2@ @ std@ @A) 1>c:\users\innersoft\documents\visual studio 2012\Projects\CPractice\Debug\CPractice.exe : fatal error LNK1120: 1 unresolved externals ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 

and here is my code

 #include <iostream> #include <stdio.h> #include <cstdlib> #include <string> using namespace std; class CPractice { public: static void setName(string s) { name = s; } static string getName() { return name; } private: static string name; }; int main() { CPractice::setName("Name"); cout << "\n" << CPractice::getName(); system("PAUSE"); return EXIT_SUCCESS; } 
+6
source share
4 answers
 static string name; 

Since this is static , this line only declares name - you also need to define it. Just put this below your class definition:

 string CPractice::name; 

If you move your class to the appropriate header and implementation file, make sure you put this definition in the implementation file. It must be defined in only one translation unit.

+18
source

I think you are trying to compile with gcc when you should compile with g++ . For more details, see What is the difference between g ++ and gcc? .

You also need to add string CPractice::name; below your class definition.

+1
source

You just declared name in the class, static variables should be defined as outside the class:

 string CPractice::name ="hello" ; 
+1
source

Since the name is a static data member, you should initialize it :) and not rely on the constructor associated with the default instance.

Add this after the class definitions (yep, I know that it is confusing since your member is private, but this is just initialization):

 string CPractice::name; 
+1
source

All Articles