I was recently having some "undefined reference" errors that I managed to resolve but I don't understand why the solution works. I have the following main source file:
Main.cpp:
#include <iostream>
#include "Log.h"
int main()
{
std::cout << "Hello World!" << std::endl;
Log log;
log.SetLevel(Log::LevelWarning);
log.Error("Hello!");
log.Warning("Hello!");
log.Info("Hello!");
std::cin.get();
}
which references a class declared in a separate source file:
Log.cpp:
#include <iostream>
class Log
{
public:
enum Level
{
LevelError, LevelWarning, LevelInfo
};
private:
Level m_LogLevel = LevelInfo;
public:
void SetLevel (Level level)
{
m_LogLevel = level;
}
void Error (const char* message)
{
if (m_LogLevel >= LevelError)
std::cout << "[ERROR]: " << message << std::endl;
}
void Warning (const char* message)
{
if (m_LogLevel >= LevelWarning)
std::cout << "[WARNING]: " << message << std::endl;
}
void Info (const char* message)
{
if (m_LogLevel >= LevelInfo)
std::cout << "[INFO]: " << message << std::endl;
}
};
Log.h:
#pragma once
class Log
{
public:
enum Level { LevelError, LevelWarning, LevelInfo };
private:
Level m_LogLevel;
public:
void SetLevel (Level);
void Error (const char*);
void Warning (const char*);
void Info (const char*);
};
The code above gives me the linker errors "undefined reference to Log::..." for all members of the class Log being called in Main.cpp. Searching around I eventually found comment saying something along the lines of "static members and functions should be initialized", which gave me the idea of adding the following:
void Init()
{
Log log;
log.SetLevel(Log::LevelInfo);
log.Error("NULL");
log.Warning("NULL");
log.Info("NULL");
}
To my Log.cpp file. This amazingly solves the issue and the project builds successfully, but these members are not declared as static and so I don't understand why this works, or even if this is the correct solution.
I'm using gcc in linux and compiling with "g++ Main.cpp Log.cpp -o main". Source files are in the same folder.