Hi iam begginer at c++ i have class with static methods and i cant access them it throws me 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;
}
There is an unresolved external symbol error from many of these errors in C++ so far. It may occur within your code while compilation when you miss some function definition, some library is missing for the usage of definitions, some external variable has been defined in the code, or some unfound file has been included in the code.
So when we try to assign it a value in the main function, the linker doesn’t find the symbol and may result in an “unresolved external symbol” or “undefined reference”. The way to fix this error is to explicitly scope the variable using ‘::’ outside the main before using it.
The linker must resolve, or find the matching definition for, every external symbol referenced by each object file. The linker generates an error when it can't resolve an external symbol. It means the linker couldn't find a matching exported symbol definition in any of the linked files. Compilation and link issues
An external symbol is one referenced in one object file, but defined in a different library or object file. An exported symbol is one that's made publicly available by the object file or library that defines it. To create an application or DLL, every symbol used must have a definition.
static string name;
As it is static
, this line only declares name
- you need to define it too. Simply place this below your class definition:
string CPractice::name;
If you end up moving your class to a corresponding header and implementation file, make sure you place this definition in the implementation file. It should only be defined in a single translation unit.
You only declared name
in the class, static variables need to be defined like so outside of the class:
string CPractice::name ="hello" ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With