Compiling multiple C files in a program

前端 未结 4 1908
你的背包
你的背包 2020-12-05 08:32

I have the following two files:

file1.c

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

file2.c



        
相关标签:
4条回答
  • 2020-12-05 08:38

    You can, but you shouldn't.

    Use a header file, file2.h:

    // file2.h
    
    void foo(); // prototype for function foo()
    

    Then add:

    #include "file2.h" 
    

    in file1.c

    To compile:

    $ gcc -Wall file1.c file2.c -o foo
    

    As a general rule it's better (more robust) to use a header file to define the interface of each module rather than ad hoc prototypes within dependent modules. This is sometimes known as the SPOT (Single Point Of Truth) principle.

    0 讨论(0)
  • 2020-12-05 08:38

    It's ugly, but using gcc, you could:

    gcc -include file2.c file1.c
    

    -include is a flag to the preprocessor which will include the contents of file2.c at the very top of file1.c. Having said that, it's a poor choice, and breaks down for all but the simplest of programs.

    0 讨论(0)
  • 2020-12-05 08:52

    You don't need an extern, but file1.c must see a declaration that foo() exists. Usually this declaration is in a header file.

    To add a forward declaration without using a header file, simply modify file1.c to:

    int foo();  // add this declaration
    
    int main(){
      foo();
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-05 09:00

    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 
    $ 
    
    0 讨论(0)
提交回复
热议问题