q57259028
q57259028

Reputation: 59

How to fix problems when linking cpp files?

Config.h:

#ifndef CONFIG_H
#define CONFIG_H
class Config {
 public:
  static int GetDefult();
};
#endif //CONFIG_H

Config.cpp:

#include "Config.h"
int Config::GetDefult(){
 return 1;
}

main.cpp:

#include "Config.h"
#include<iostream>
using namespace std;
int main()
{
  cout << Config::GetDefult() << endl;
}

When my main file is linking, it prompts undefined references:

/tmp/ccD7rrRH.o: In function `main':
main.cpp:(.text+0x5): undefined reference to `Config::GetDefult()'
collect2: error: ld returned 1 exit status

How to include the .h file and make the program run successfully?

Upvotes: 2

Views: 120

Answers (1)

Yunnosch
Yunnosch

Reputation: 26703

Playing with the shown code (the more useful one from first versio of your question and after fixing the differences to a MRE with wild guesses),
I got mostly "is not a member of class Config".

I got it to build like below; because obviously you can fix that error by making them members of that class. I chose private because it seems appropriate, but that is not needed for the solution of your problem.

#ifndef CONFIG_H
#define CONFIG_H
#include <mutex>

using namespace std;
class Config {
 public:
  static Config* GetDefult();
 private:
  static Config* p_instance;
  static mutex mutex_;
};
#endif //CONFIG_H
//Config.cpp
#include "Config.h"


Config* Config::GetDefult()
{
    return Config::p_instance; // just to fix building, wild guess
}

Config* Config::p_instance;
mutex Config::mutex_;

However, please do not using namespace std; in a header.

Upvotes: 1

Related Questions