Linking error when include C in C++

Hi everyone,

Somebody can help me. How do I compile this files?

1
2
3
4
5
6
// c.h
#ifndef WOW_H
#define WOW_H
int x;
int h();
#endif 


1
2
3
4
5
//c.c
#include "c.h"
int h(){
	return x;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
// b.h
#ifndef B_H
#define B_H
extern "C" {
	#include "c.h"
}

class b{
	public:
	b();
	int g();
};
#endif 


1
2
3
4
5
6
7
// b.cpp
#include "b.h"
b::b()
{}
int b::g(){
	return x+h();
}


1
2
3
4
5
6
7
8
// main.cpp
#include "b.h"

int main(){
	b obj;
	obj.g();
	return 0;
}


I have tried with:
g++ b.cpp main.cpp c.c

but I obtain this errors:

/tmp/ccd2Ed7I.o:(.bss+0x0): multiple definition of `x'
/tmp/cc6G2vTb.o:(.bss+0x0): first defined here
/tmp/ccAjxYki.o:(.bss+0x0): multiple definition of `x'
/tmp/cc6G2vTb.o:(.bss+0x0): first defined here
/tmp/cc6G2vTb.o: In function `b::g()':
b.cpp:(.text+0x21): undefined reference to `h'
collect2: ld returned 1 exit status


My compiler is g++ 4.3.2

in advance thanks and regards
You're problem is that you are including the header file in all the cpp files and compiling them all simultaneously. the "ifndef" works for one cpp file and multiple header files calling it, but not between multiple source files. I never understood that my self but I learned to except it :O
You can't define globals this way. A global can only exist in one source file. When you put a global in a header and the #include it in multiple cpp files, each cpp file makes its own global var, and then the linker doesn't know which one to use.

It's the same idea as having a function body in multiple cpp files. You just can't do it.

The solution here:

get rid of the global 'x'. Globals are poor design anyway.
Topic archived. No new replies allowed.