[C] Header Problem

Two C source files include a single header file. The header file contains a declaration of a constant variable. However, the declaration prevents me from compiling and/or linking.

1
2
3
4
5
6
7
8
9
10
//main.h

#ifndef MAIN_H
#define MAIN_H

const int number = 1;

void f();

#endif 


1
2
3
4
5
6
7
8
9
//main.c

#include "main.h"

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


1
2
3
4
5
6
7
8
//main2.c

#include "main.h"

void f()
{

}


If I remove const int number = 1; it doesn't produce an error. How can I keep the declaration and have it work properly?
Last edited on
It all depends on what you want.
1. Do you want a single global variable called number that's available to both units?
2. Do you want two distinct variables called number visible to each unit?

Like us, the compiler doen't know what you want.
Last edited on
I want it to exist as a single global variable available to both files.
Last edited on
One unit needs to see:
const int number = 1;
This defines number and allocates storage for it.

The other(s) needs to see:
extern const int number = 1;
This simply declares number and leaves it to the linker to sort out.

Often a macro is used to reconcile this. e.g.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//main.h

#ifndef MAIN_H
#define MAIN_H

#ifdef DEFINE_GLOBALS
#define EXTERN
#else
#define EXTERN extern
#endif

EXTERN const int number = 1;

void f();

#endif  


1
2
3
4
5
6
7
8
9
//main.c
#define DECLARE_GLOBALS
#include "main.h"

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


1
2
3
4
5
6
7
8
//main2.c

#include "main.h"

void f()
{

}
If they were two distinct variables, would it abolish the need for the macro?
If they were two distinct variables, you'd need to declare them static in each compiled unit.

Have a look at the treatment of errno in the C header files. errno is a global available to all C/C++ compiled units and so is declared extern int errno;
Last edited on
Topic archived. No new replies allowed.