I am trying a code which has two C++ files(client.cpp
and server.cpp
) and one common.h
header file which contais a class and functions.
If client stops execution server should stop as well. For that purpose I thought of a global variable as suggested in :How do I use extern to share variables between source files?
but it didn't work out for me.
Error : when I tried g++ server.cpp common.h -o server
:
/tmp/ccjoNSQd.o: In function `main':
server.cpp:(.text+0x3a): undefined reference to `ch'
collect2: error: ld returned 1 exit status
client.cpp:
#include "common.h"
int ch=1;
int main()
{
random r;
do{
cout<<"Do you want to continue: 1=yes 0=no "<<endl;
cin>>ch;
r.display();
}while(ch==1);
}
server code:
#include "common.h"
int main()
{
random r;
do{
cout<<"display in server"<<endl;
r.display();
}while(ch==1);
}
common.h:
#ifndef COMMON_H
#define COMMON_H
#include <iostream>
using namespace std;
extern int ch;
class random
{
public:
void display()
{
cout<<"HELLO_WORLD"<<endl;
}
};
#endif
I want to include the common.h in both the files . So according to How do I use extern to share variables between source files? I've written extern int ch
in common.h
and used ch
in both source files.