Home > Back-end >  How to use a function from another .c file?
How to use a function from another .c file?

Time:01-29

I'm using RTKLIB (it is not important), and inside a directory there are multiple .c files:

rtcm.c
rtmc2.c
rtcm3.c

etc. etc.

Inside the same directory, I created a main.c file, where the program is executed. Inside main.c I call different functions that are defined in the different .c files.

There is only one .h file, which is rtklib.h, inside which, there are only struct definitions (there are not the declarations of the functions inside the other .c files).

How can I call, inside the main.c file, a function defined inside the rtcm.c file, for example?

How can I create a makefile that allows me to include all the .c file in when I compile?

CodePudding user response:

You need to declare the prototype of the function you want to export. Usually you would do that in the corresponding .h file.

A prototype mirrors the declaration of the function, just without the braces. So the prototype of int someFunction(int parameter) {} is, in fact, int someFunction(int parameter);.

Simply write the header of your function to your header file (or the .c file you want to use it in) and you're good.

Example:

rtcm.c:

int myFunction(int parameter1)
{
    //Does something
}

rtcm.h:

int myFunction(int parameter1);

main.c:

#include "rtcm.h"

int main(int argc, char *argv[])
{
    myFunction(5);
}

CodePudding user response:

You probably don't want to do this at all. If you have a library, you should install it and link with the installed version. If you really do want to build an executable without installing the library, you could use a GNUmakefile like:

SOURCES := $(wildcard *.c)
OBJ := $(patsubst %.c,%.o,$(SOURCES))
    
main: $(OBJ)
        $(CC) $^ -o $@

For other versions of make, you can do something similar. Let make use its default rules to build the object files. All you need to do is list those object files on the final build line so the tool chain can build the executable.

  •  Tags:  
  • Related