Home > Software design >  Can we have multiple c files to define functions for one header file?
Can we have multiple c files to define functions for one header file?

Time:02-18

Newbie to C and C .

I have one .h file in which some functions are declared. I'm trying to implement the functions in two separate .c files, but when compiling I got a linker error.

Is it not allowed?

CodePudding user response:

Yes it is allowed. Here is a very simple example:

foobar.h: declares foo and bar

void foo(void);
void bar(void);

foo.c: implements foo

#include <stdio.h>
#include "foobar.h"

void foo(void)
{
  printf("foo\n");
}

bar.c: implements bar

#include <stdio.h>
#include "foobar.h"

void bar(void)
{
  printf("bar\n");
}

main.c: uses foo and bar

#include <stdio.h>
#include "foobar.h"

int main(void) {
  foo();
  bar();
  return 0;
}

Compiling, linking and running with gcc:

$ gcc foo.c
$ gcc bar.c
$ gcc main.c
$ gcc -o someprog foo.o bar.o main.o
$ ./someprog
foo
bar
$

or

$ gcc -o someprog foo.c bar.c main.c
$ ./someprog
foo
bar
$
  • Related