explorer
explorer

Reputation: 952

Is it possible to compile multiple dependent C files, without creating header file?

I am having some issues with putting multiple .c files together. I will mimic my situation with the following files.

mod.c

#include <stdio.h>
void print_hello() {
  printf("Hello!");
}

mod_main.c

#include "mod.c"
int main() {
  print_hello();
}

Compiling scenarios:

#1

$ cc -o mod_main mod_main.c
# No errors

#2

$ cc -c -o mod_main.o mod_main.c
$ cc -c -o mod.o mod.c
$ cc -o mod_main mod.o mod_main.o
duplicate symbol '_print_hello' in:
    mod.o
    mod_main.o
ld: 1 duplicate symbol for architecture x86_64

#3

$ cc -o mod_main mod.c mod_main.c
duplicate symbol '_print_hello' in:

Based on these attempts, I gather that, I can compile simply mod_main.c & get it working. Or, I can create a .h file as follows & get it working.

mod.h

void print_hello(void);

mod.c

#include <stdio.h>
#include "mod.h"
void print_hello() {
  printf("Hello!");
}

mod_main.c

#include "mod.h"
int main() {
  print_hello();
}

I like to know, if there are any other ways to compile multiple C files that has dependencies within each other. To be precise, is there a decent way to avoid writing header files?

Good day!

PS: I have explored similar questions on StackOverflow. None of them that I could find where asking the exact questions as mine.

Upvotes: 1

Views: 705

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409364

First of all, including source files is generally a bad idea.

As for the problem itself, you can easily solve it by pretending you're writing a header file, but instead write all declarations, structure definitions and macros in a source file. Then copy-paste it into the other source files who needs it.

But, and this is a very important but, this is extremely error-prone. If the signature (e.g. argument list) of a function changes, or a structure is modified, or a macro gets a different value, then you must remember to modify this everywhere. If you have more than a couple of source files it becomes easy to miss one of the files.

If a function with the wrong signature is called, or you have structures that are not character-by-character copies of each other, then that will lead to undefined behavior. Mismatching macros might not be so serious, but if it's an array-limit that is changed (for example) then it's easy to go out of bounds where you miss to update the macro.

In short: It's possible, but not a good idea. Use one or more header files for common declarations, structures and macros.

Upvotes: 3

Related Questions