0

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
Zonko
  • 125
  • 4
  • 2
    Questions about compiler errors should always include the complete error message. – user694733 Feb 03 '17 at 12:29
  • Will do that next time, I thought it wasn't necessary because it wasn't an explicit error, but me getting the system behind includes wrong. – Zonko Feb 03 '17 at 12:33
  • Personally, I don't like `#pragma once`. It's non-standard, and it has one serious and IMO fatal flaw. See http://stackoverflow.com/questions/787533/is-pragma-once-a-safe-include-guard – Andrew Henle Feb 03 '17 at 12:40
  • Thanks, going to change that. – Zonko Feb 03 '17 at 12:44

1 Answers1

1

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).

Vittorio Romeo
  • 82,972
  • 25
  • 221
  • 369