I have a header file A.h
in which i define a const int ID = 4;
. I have included this header file in to C files A.c
and main.c
. I have used header guards #ifndef A_H #define A_H
etc. But I get the error multiple definition of ID
when I try to compile the code.
I read somewhere that this can, in most cases, be avoided by using #pragma once
but I still get the error.
My question is that how can I define variables in C? Should I have to move definition of ID to C file but then I have to declare it in every file I use? Or using extern
the only way in this situation?
Asked
Active
Viewed 797 times
-1

ata
- 8,853
- 8
- 42
- 68
-
http://stackoverflow.com/questions/1433204/what-are-extern-variables-in-c – cnicutar Sep 10 '12 at 15:55
2 Answers
2
In C you are only allowed to have a single definition per object. Include guards and similar don't help on this if you have multiple .o
files (compilation units). Each of them has a copy, which is not allowed.
If you don't need the address of that object and you are only interested in its constant value you can replace it by
enum { ID = 4 };
This defines a named value ID
of type int
that you easily can put in a header file.

Jens Gustedt
- 76,821
- 6
- 102
- 177
1
Yes, using extern
is the only solution. pragma
or include guards guard against multiple inclusion in the same translation unit, this is a multiple definition error.

Luchian Grigore
- 253,575
- 64
- 457
- 625