简体   繁体   中英

Call external function written in C from another file written in C in a Linux enviroment

I am having trouble calling an external function I wrote in the Pico editor in linux. The program should call an external function and they are both written in C.

#include????

void calcTax()
float calcfed()
float calcssi()

// stub program

#include"FILE2"???or do I use"./FILE2"// not sure which to use here or what        extension     the file should have. .c or .h and if it is .h do I simply change the file     name to file.h?
#include<stdio.h>
#define ADDR(var) &var

extern void calctaxes()
int main()
{
}

I am using gcc to compile but it will not compile. both files are in the same directory and have the .c extension

I am a new student so bear with me.

Normally, when you want a function in one compilation unit to call a function in another compilation unit, you should create a header file containing the function prototypes. The header file can be included in both compilation units to make sure that both sides agree on the interface.

calctax.h

#ifndef calctax_h_included
#define calctax_h_included

void calctaxes(void);
/* any other related prototypes we want to include in this header */

#endif

Note that extern is not required on functions, only global data. Also, since the function takes no arguments, you should put void in the argument list, and you also need a semi-colon at the end of the prototype.

Next, we can include this header file in the .c file that implements the function:

calctax.c

#include "calctax.h"

void calctaxes(void)
{
    /* implementation */
}

Finally, we include the same header file in our main .c file that calls the function:

main.c

#include "calctax.h"

int main(int argc, char **argc)
{
    calctax();
    return 0;
}

You can compile and link these together with

% gcc -o main main.c calctax.c

Normally you don't want to include .c implementation files. The normal thing to do is have two source files that you build into objects:

cc -o file1.o file1.c
cc -o file2.o file2.c

And then link them into an executable at the end:

cc -o example file1.o file2.o

To allow calling functions between the two .c files, you create a header ( .h ) file that has function declarations for everything you're interested in sharing. For you, that might be something like header.h , containing:

void calcTax(void);
float calcfed(void);
float calcssi(void);

Then, just #include "header.h" from the implementation files where you need to know about those functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM