Alex Rivera | Logout

How do header and source files in C work?

Asked 2011-05-05T21:52:48.270
77

I've perused the possible duplicates, however none of the answers there are sinking in.

tl;dr: How are source and header files related in C? Do projects sort out declaration/definition dependencies implicitly at build time?

I'm trying to understand how the compiler understands the relationship between .c and .h files.

Given these files:

header.h:

int returnSeven(void);

source.c:

int returnSeven(void){
    return 7;
}

main.c:

#include <stdio.h>
#include <stdlib.h>
#include "header.h"
int main(void){
    printf("%d", returnSeven());
    return 0;
}

Will this mess compile? I'm currently doing my work in NetBeans 7.0 with gcc from Cygwin which automates much of the build task. When a project is compiled will the project files involved sort out this implicit inclusion of source.c based on the declarations in header.h?

Edit
Report

1 Answer

2

The compiler itself has no specific "knowledge" of relationships between source files and header files. Those types of relationships are typically defined by project files (e.g., makefile, solution, etc.).

The given example appears as if it would compile correctly. You would need to compile both source files and then the linker would need both object files to produce the executable.

answered 2011-05-05T21:58:52.923

Your Answer