Software_t
Software_t

Reputation: 586

How can I call to function that exists in other file?

Given 2 files, for examples:

file1.c :

int main(){
  f();
  return 0;
}

file2.c:

void f(){
  return;
}

Why I can't call f from file1.c like that?

Upvotes: 0

Views: 57

Answers (2)

r3mus n0x
r3mus n0x

Reputation: 6144

Because first you need to tell the compiler (declare) that it exists somewhere:

void f(); //function declaration

int main()
{
    f();
    return 0;
}

Usually, though, it is better to put such declarations in a separate header file (e.g. file2.h) so that later you could include this file (e.g. #include "file2.h") instead of duplicating such declaration in every other file where you need this function.

Upvotes: 3

klutt
klutt

Reputation: 31296

The problem is that file1.c does not "know" that the function f exists. You need to use a prototype. The standard way is to put prototypes in header files and definitions in .c files.

It could look like this:

file1.c:

#include "file2.h"
int main(){
  f();
  return 0;
}

file2.h:

#ifndef FILE2_H
#define FILE2_H
void f();
#endif

file2.c:

#include "file2.h"
void f(){
    return;
}

Upvotes: 0

Related Questions