The following program compiles just fine in C, but not in C++. Can
anyone explain why? I have a chunk of code that defines stuff like
this in headers (without the extern) that I can not easily change.
The C compiler recognizes the first foo and second foo as the same.
The C++ compiler not so much.
Is there a way to get this to compile in C++ without changing all the
headers?
int foo;
int foo=1;
In C, each of these is (separately) a "tentative definition". You can
have as many tentative definitions for a variable as you like, as long
as none of them directly conflicts with any other. After reading all the
tentative definitions, the compiler creates a complete definition of the
variable based on 1) the defaults from where those definitions are
placed, and 2) all the storage classes, qualifiers, etc. you put into
all the tentative definitions. As I said, as long as nothing you put
into one tentative definition directly conflicts with what you put in
another (e.g. defining foo as an int in one place but a double in
another) this is allowed. For example:
int foo;
extern int foo;
volatile int foo;
int foo = 1;
In this case, the overall definition is equivalent to:
extern volatile int foo = 1;
In C++, there's no such thing as a tentative definition. There's a one
definition rule that says you have to define the variable exactly once
and that's it. There's almost certainly not going to be a way to
persuade a C++ compiler to accept your definitions as they stand right
now.
As to how to make things work: I'm pretty sure you're not going to be
able to persuade a C++ compiler to accept the source code as it stands,
so it's basically going to come down to whether you can find a tool to
generate what you need. Offhand I'm not sure whether it can do the job
or not, but the first one I'd look at would probably be Doxygen.