I'm trying to create a header file, implementation file and main file for a simple c++ program that returns the systems hostname using gethostname().
my header file that declares my class, data, and methods
//hostname.h
#pragma once
namespace hostnamespace
{
class hostname_class
{
public:
hostname_class();
void to_string();
private:
char *name;
};
}
my implementation file that defines my class and methods
//hostname_class.cpp
#include "hostname.h"
#include <iostream>
#include <unistd.h>
#include <limits.h>
using namespace hostnamespace;
using namespace std;
class hostname_class{
private:
char *name;
public:
hostname_class(){
gethostname(name, HOST_NAME_MAX);
}
void to_string(){
cout << "Hostname:" << &name << endl;
}
};
my main program file
//hostname_main.cpp
#include "hostname.h"
#include <iostream>
using namespace hostnamespace;
int main() {
hostname_class host;
host.to_string();
return 0;
}
when I try and run g++ -o main hostname_main.cpp hostname_class.cpp
I get this error
/bin/ld: /tmp/ccGfbyuu.o: in function `main':
hostname_main.cpp:(.text+0x1f): undefined reference to `hostnamespace::hostname_class::hostname_class()'
/bin/ld: hostname_main.cpp:(.text+0x2b): undefined reference to `hostnamespace::hostname_class::to_string()'
collect2: error: ld returned 1 exit status
any help would be appreciated.
hostname_classin both the header and cpp. Don't do that. Just implement the members in the cpp . In case you're wondering how on earth this compiled to the point of link failure, you have twohostname_classclasses: one in thehostnamespacenamespace, and one in the global namespace. The code inhostname_class.cppimplements the one in the global namespace, while theusing namespace hostnamespace;inmain.cpppulls in the other one (which you never defined).gethostnamedoesn't work this way because C arrays and strings don't work this way.