Reputation: 125
I'm currently working on a c project and to keep my code organized I use include files. One file includes.h
has a typedef
and I wan't to access this in a different included file util.h/util.c
. I included them both in main.c
in the following order: includes.h
util.h
.
main.c
:
#include <stdio.h>
#include <stdlib.h>
//similar includes
#include "includes.h"
#include "util.h"
int main()
{
MyStructType somename;
somename.number = 5;
util_foo(somename);
return 0;
}
includes.h
:
#pragma once
struct structname
{
int number;
};
typedef struct structname MyStructType;
util.h
:
#pragma once
#include "includes.h" //added line (>accepted answer)
int util_foo(MyStructType blabla);
util.c
:
#include <stdio.h>
#include "util.h"
int util_foo(MyStructType blabla)
{
printf("%d\n", blabla.number);
return 0;
}
I compile with this command: gcc -o main *.c
But this doesn't compile, do you have any idea why this doesn't work? Or how to fix it without changing my projects' structure completely?
Edit:
It is recommended to replace #pragma once
with:
#ifndef STH_SIMILAR_TO_FILENAME
#define STH_SIMILAR_TO_FILENAME
//code
#endif
Upvotes: 0
Views: 2689
Reputation: 93324
You need to add
#include "includes.h"
in util.h
in order to make your code compile.
This is because you're relying on transitive #include
directives to get the MyStructType
typedef into util.h
from main.c
, but you're not doing the same in util.c
.
The best solution (for maintainability purposes) is to minimize relying on transitive inclusions: you should include includes.h
wherever it's needed (in this case, in util.h
).
Upvotes: 1