Inclusion guards...

Started by
2 comments, last by Kamataat 20 years, 8 months ago
Hey! Could anyone tell me why the following inclusion guard isn''t working? //main.cpp

#include <iostream>
#include "int.h"

using namespace std;

void F();

int main()
{
	cout << a << endl;

	F();

	system("PAUSE");

	return 0;
}
//other.cpp

#include <iostream>
#include "int.h"

using namespace std;

void F()
{
	cout << a + 10 << endl;
}
//int.h

#ifndef __TEST2_H__
#define __TEST2_H__

int a = 10;

#endif
I''m using MinGW with GCC 3.2 and compile with the following: g++ -o main *.cpp
Advertisement
You shouldn''t declare variables like that in header files. Make it an extern declaration instead, and actually fully declare the variable in a source file.
You can''t define the global symbol "a" in more than one translation unit. Both translation units are exporting the symbol "a". Two solutions:

1) In the header change the line to "extern int a;" and then in some .cpp file "implement" a with a line something like "int a = 10;".

2) Either declare "a" as static or in an unnamed namespace so each file has its own, unexported, "a".

Also, if I remember correctly, the symbol __TEST2_H__ is reserved for the compiler (as is any symbol starting with a double underscore or an underscore followed by a capital letter), so you should use something else (I like H_MYPREFIX_MYMODULE because H_ isn''t reserved for anything by the standard, H_MYPREFIX is unlikely to be used by anyone else, and identifiers starting with a capital E are reserved by errno.h and probably cerrno)
Allright, I got it to work now. Thanks!

This topic is closed to new replies.

Advertisement