pepelu
pepelu

Reputation: 388

Declaring variable in C header

I want to include a variable declared in an external file in C.

My project structure looks like this.

foo.h
foo.c
variable.c
main.c

What I'm doing right now is

/* main.c */

#include "foo.h"

#include <stdio.h>
#include <stdlib.h>


int main() {
    bar();
    printf("%d\n", a);
    return 0;
}

/* foo.h */

#ifndef FOO_H
#define FOO_H

#include "variable.c"

extern const int a;
extern const int b[];


int bar();
#endif

/* foo.c */

#include "foo.h" 
#include <stdio.h>

int bar () {
    printf("tururu\n");
    printf("%d\n", b[0]);
    return 0;
}

/* variable.c */

const int a = 2;
const int b[3] = {1, 2, 3};

The variables I want to define this way are constant (read-only).

I do not know beforehand the size of the array, it depends on the definition in variable.c.

So my question is:

Thank you

EDIT: I have updated my code with an example that can be tested. This code is not compiling because it says 'b' is undeclared in function bar. If I comment out the printf in bar it compiles and run. So the variables can be seen by main but not by foo.c?

EDIT2: Variables included this way are read-only. I have updated the code and add the include of foo.h in foo.c and now the compiler tell that there are multiple definitions of 'a' and 'b'

EDIT3: Clean up the code and the question trying to be more clear.

Upvotes: 1

Views: 3212

Answers (3)

user3079266
user3079266

Reputation:

Remove #include "variable.c" from foo.h, and your code should work.

You're basically using extern to tell your compiler that whatever you use in a declaration after the extern keyword will be defined in another .c source file that is linked separately. In your case, this .c file is variable.c.

And yeah, take care to never #include .c files. This can easily lead to the linker going haywire.

Upvotes: 2

simon_xia
simon_xia

Reputation: 2544

It is a good practice to declare variable in header file and define in c file

more detail: Variable Definition vs Declaration

In your variable.h, you just define two variable

So, it is not the proper way

Besides the code related to the array is not wrong, you can put it in a .c file

Upvotes: 1

AndreaPomatto
AndreaPomatto

Reputation: 21

The variables must be defined in a c file, while in the header you can put the extern reference

/* foo.h */
#ifndef FOO_H
#define FOO_H

#include "variable.h"

extern int a;
extern int b[];

#endif

/* foo.c */

int a = 2;
int b[3] = {1, 2, 3};

Upvotes: 2

Related Questions