K
K
ks02014-10-02 17:58:07
C++ / C#
ks0, 2014-10-02 17:58:07

Why doesn't an error occur when declaring a variable in a .h file?

AVR and GCC, AVR are controllers, who do not know. But this should not affect the essence.
C program. I declare a variable in .h, just int var;
In two .s files I do #include and refer to this variable. I look with a debugger - there is one variable, at one address in memory.
At the same time, such a construction is prohibited in the literature, because should cause a double definition, in theory the linker should swear. It is correct to write extern int var in the header, and make the declaration in some .c file. What's happening?

// test.c
#include "module.h"
void main()
{	
  var=0;
  inc();
  var++;
}

// module.h
#ifndef _MODULE_H
#define _MODULE_H
int var;
void inc();
#endif

// module.c
#include "module.h"
void inc()
{
  var++;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2014-10-02
@ks0

This can be done in C, this is a tentative definition, the object declared in this way falls into the general data area. When linking objects with the same name in this area become one object.
You can't do that in C++.
extern int var is the declaration. It is correct to make the definition in one .c file.

A
Alex Chistyakov, 2014-10-02
@alexclear

I don’t know in what literature what is forbidden, but in gcc we have this:

[email protected] ~ cat test.h 
int i;
[email protected] ~ cat test.c
#include "test.h"
#include <stdio.h>

int main (void) {
i = 10;
printf("%i\n", i);
return 1;
}
[email protected] ~ gcc test.c -o test.out
[email protected] ~ ./test.out
10
[email protected] ~

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question