Kobi Burnley
Kobi Burnley

Reputation: 107

including c file includes by header file

I have those 3 files in my workspace:

1.h

#ifndef SOME_HEADER_FILE_H
#define SOME_HEADER_FILE_H
//code
#endif

1.c

#include <stdio.h>
#include "1.h"
//code

main.c

#include "1.h"
int main(){
    printf("hello");
}

but in main.c printf is unidentified, is there a way to make it work while the relevant header is called in 1.c? how can I link the 1.c and 1.h files?

edit: it's an academic assignment and I'm not allowed to make changes in the main and header.

Upvotes: 0

Views: 67

Answers (2)

James Sullivan
James Sullivan

Reputation: 126

Because of the way the #include macro works (it expands the whole header file that you include at the line where you call the macro), you actually don't need to include stdio.h within main.c as long as stdio.h is included in a header file that main.c includes.

Hopefully this makes it clear:

main.c

#include "test.h"

int main()
{
    printf("I can call this function thanks to test.h!\n");
    return 0;
}

test.h

#include <stdio.h>

This will work just fine.

But this is not the same as being able to use a function that a .c file has access to based on its own #include definition just because you cross-compiled them. In that case the other.c file that calls #include <stdio.h> will get printf(), but main.c does not.

In this setup,

main.c

int main()
{
    printf("I don't have any way to call this...\n");
    return 0;
}

test.c

#include <stdio.h>

You will not have any way for main to know what printf() is, even if you cross-compile the two. test.c knows what printf() is but not main.

What you want is to have #include <stdio.h> in other.h, and then #include "other.h" in main.c.

But for future reference, this is probably poor practise as it should be immediately apparent what each file's requirements are so that you get a good sense of what its job is.

So here's what I would probably suggest as the best solution:

main.c

#include <stdio.h>


int main()
{
    printf("I can call this all on my own.\n");
    return 0;
}

Upvotes: 0

P.P
P.P

Reputation: 121417

You have included #include <stdio.h> only in 1.c, not in 1.h or main.c. Obvious solution is to include it in main.c.

Upvotes: 1

Related Questions