I’m a complete newbie to C++ so bear with me. I am defining a class called ‘logging’ which is currently write in main.cpp. Now that I am trying to split implementation (log.cpp) from declaration (log.h), I have the following situation that bring me to compiler error ‘identifier logging is undefined’:
log.cpp
#include <iostream>
#include <unordered_map>
#include <string>
#include "..\h\log.h"
class logging {
public:
std::unordered_map<int, std::string> m_log_levels;
logging() {
m_log_levels[2] = "info";
m_log_levels[1] = "warning";
m_log_levels[0] = "error";
}
private:
int m_level = 2;
public:
void setLevel(int level) {
m_level = level;
}
void log(const char* message) {
std::string sm = "[" + m_log_levels.at(m_level) + "]: ";
std::cout << sm + message << std::endl;
}
};
log.h
#pragma once
#include <unordered_map>
#include <string>
class logging {
public:
std::unordered_map<int, std::string> m_log_levels;
private:
int m_level;
public:
void setLevel(int level);
void log(const char* message);
};
main.cpp
#include <iostream>
#include "..\h\log.h"
int main() {
logging logger; /* -> identifier logging is undefined */
}
Build started...
1>------ Build started: Project: learn, Configuration: Debug x64 ------
1>log.cpp 1>main.cpp
1>C:\Users\pietr\source\repos\learn\learn\src\main.cpp(8,2): error C2065: 'logging': undeclared identifier
1>C:\repos\learn\learn\src\main.cpp(8,10): error C2146: syntax error: missing ';' before identifier 'logger'
1>C:\repos\learn\learn\src\main.cpp(8,10): error C2065: 'logger': undeclared identifier 1>Generating Code...
1>Done building project "learn.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
>Solution :
The main problem is that you’re defining the class logging twice. Instead you should put the class definition with only the declaration of the members functions in the header and then implement the member functions in the source file as shown below:
log.h
#pragma once
#include <unordered_map>
#include <string>
class logging {
public:
std::unordered_map<int, std::string> m_log_levels;
private:
int m_level;
public:
logging(); //declaration for default constructor
void setLevel(int level); //this is declaration
void log(const char* message); //this is declaration
};
log.cpp
#include <iostream>
#include <unordered_map>
#include <string>
#include "log.h"
//definition of default ctor using member initializer list
logging::logging() :m_log_levels{{0, "error"},{1, "warning"}, {2,"info"}}, m_level(2){
}
//this is definition of member function
void logging::setLevel(int level) {
m_level = level;
}
//this is definition of member function
void logging::log(const char* message) {
std::string sm = "[" + m_log_levels.at(m_level) + "]: ";
std::cout << sm + message << std::endl;
}
main.cpp
#include "log.h"
int main()
{
logging log;
return 0;
}