Search code examples
cstructcompilationconsoleconsole-application

C console application - file/header organization and compiling


I'm having a hard time organizing multiple .c and .h files into my console application project - and also, I'm a little unsure on how the compiling command should be written. I'm gonna list my files and the (relevant) code on them:

main.c:

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

int main () {
    ...
    search();
    ...
    return 0;
}

structs.c:

#include <structs.h>

typedef struct {
    ...
} Brand;

typedef struct {
    ...
} Car;

structs.h:

#ifndef STRUCTS_H
#define STRUCTS_H

typedef struct {
    ...
} Brand;

typedef struct {
    ...
} Car;

#endif

search.c:

#include <search.h>

Car *search () {
    ...
    Car cars[255];
    ...
    return cars;
}

search.h:

#ifndef SEARCH_H
#define SEARCH_H

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

Car *search ();

#endif

The compilation command that I'm writing is gcc -o main structs.h search.h main.c. The terminal is displaying the following errors:

search.h:6:10: fatal error: structs.h: No such file or directory
main.c:6:10: fatal error: structs.h: No such file or directory

I have researched everywhere, watched C tutorials again and again, looked at some similar problems here on StackOverflow - everything I tried just switched this problem for others (other files "missing"). Thanks in advance and sorry for the sloppy english!


Solution

  • The usual method for include local include files is to put them in quotation marks rather than angle brackets.

    So your main should start with:

    #include <stdio.h>
    #include <stdlib.h>
    
    #include "structs.h" 
    #include "search.h"
    

    The compiler will check the current folder for the include files, and:

    cc -o main main.c search.c 
    

    will work. The other method to indicate to the compiler where include files are located is the -I option.

    cc -o main -I . main.c search.c
    

    Other stuff:

    "structs.h" is not a good name, it doesn't tell anyone looking at the code what the header file is for. How about "carinfo.h"?