c++clinker

Can we have multiple c files to define functions for one header file?


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?


Solution

  • 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 -c foo.c
    $ gcc -c bar.c
    $ gcc -c 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
    $