Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling multiple C files in a program

I have the following two files:

file1.c

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

file2.c

void foo(){

 }

Can I compile and link the two files together so the file1.c will recognize the foo function without adding extern?

Updated the prototype.

gcc file1.c file2.c throws: warning: implicit declaration of function foo.

like image 976
mary Avatar asked Jan 04 '12 14:01

mary


People also ask

Can you include .C files in C?

You can properly include . C or . CPP files into other source files.

Can AC program contain more than one file?

A large C or C++ program should be divided into multiple files. This makes each file short enough to conveniently edit, print, etc. It also allows some of the code, e.g. utility functions such as linked list handlers or array allocation code, to be shared with other programs.


1 Answers

The correct way is as follows:

file1.c

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

int main(void){
    printf("%s:%s:%d \n", __FILE__, __FUNCTION__, __LINE__);
    foo();
    return 0;
}

file2.h

void foo(void);

file2.c

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

void foo(void) {
    printf("%s:%s:%d \n", __FILE__, __func__, __LINE__);
    return;
}

output

$
$ gcc file1.c file2.c -o file -Wall
$
$ ./file 
file1.c:main:6 
file2.c:foo:6 
$ 
like image 137
Sangeeth Saravanaraj Avatar answered Oct 11 '22 20:10

Sangeeth Saravanaraj