1

Possible Duplicate:
How do I share variables between different .c files?

If I have two source files, and one header: file1.c, file2.c, and header.h, and:

--header.h--

int i;

--file1.c--

#include <header.h>
i = 10;

int main() {
func();
return 0;
}

--file2.c--

#include <header.h>

void func() {
printf("i = %d\n", i);
return;
}

I get the warning that i defaults to an int. What could I do if I want to have i as a float for instance?

Community
  • 1
  • 1
Iceman
  • 4,202
  • 7
  • 26
  • 39
  • If I declare i as a float, I get the 'conflicting types' error. – Iceman Oct 29 '12 at 14:02
  • Your `i = 10` is outside any function, so as such it is never executed. Instead, it is considered a variable definition that lacks a type, which the compiler fills in. However, to suggest a solution, I need to know what you are trying to achieve with this. – Jasper Oct 29 '12 at 14:04

5 Answers5

1

Make it

extern int i;

in the header and

int i = 10;

in file1.c.

The warning means that for the (incomplete) declaration i = 10; in file1.c, the "implicit int" rule is applied, in particular, that line is interpreted as a declaration (since an assignment cannot appear outside function scope).

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
1

You have a couple of errors in your code. The first is that you define the variable i in the header file, which means that it will be defined in all source files that include the header. Instead you should declare the variable as extern:

extern int i;

The other problem is that you can't just assign to variables in the global scope in file1.c. Instead it's there that you should define the variable:

int i = 10;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Declare it as extern in the header (this means memory for it is reserved somewhere else):

/* header.h */
extern int i;

Then define it in only one .c file, i.e. actually reserve memory for it:

/* file1.c */
int i = <initial value>;
Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
0
  1. In the header use

    extern int i;

  2. in either file1.c or file2.c have

    int i = 20;

  3. If you want float just change int to float

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.

In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.

In those few rare cases when you need to share a variable between files, do like this:

// file.h
extern int my_var;

// file.c
#include "file.h"
int my_var = something;

// main.c
#include "file.h"
use(my_var);

Never put any form of variable definition in a h-file.

Lundin
  • 195,001
  • 40
  • 254
  • 396