mar*_*ary 14 c linker compilation
我有以下两个文件:
在file1.c
int main(){
foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
file2.c中
void foo(){
}
Run Code Online (Sandbox Code Playgroud)
我可以将两个文件编译并链接在一起,以便file1.c识别该foo功能而不添加extern吗?
更新了原型.
gcc file1.c file2.c throws:warning:函数foo的隐式声明.
San*_*raj 31
正确的方法如下:
file1.c
#include <stdio.h>
#include "file2.h"
int main(void){
printf("%s:%s:%d \n", __FILE__, __FUNCTION__, __LINE__);
foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
file2.h
void foo(void);
Run Code Online (Sandbox Code Playgroud)
file2.c
#include <stdio.h>
#include "file2.h"
void foo(void) {
printf("%s:%s:%d \n", __FILE__, __func__, __LINE__);
return;
}
Run Code Online (Sandbox Code Playgroud)
output
$
$ gcc file1.c file2.c -o file -Wall
$
$ ./file
file1.c:main:6
file2.c:foo:6
$
Run Code Online (Sandbox Code Playgroud)
您不需要extern,但file1.c必须看到foo()存在的声明.通常,此声明位于头文件中.
要在不使用头文件的情况下添加前向声明,只需将file1.c修改为:
int foo(); // add this declaration
int main(){
foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你可以,但你不应该.
使用头文件file2.h:
// file2.h
void foo(); // prototype for function foo()
Run Code Online (Sandbox Code Playgroud)
然后加:
#include "file2.h"
Run Code Online (Sandbox Code Playgroud)
在file1.c中
编译:
$ gcc -Wall file1.c file2.c -o foo
Run Code Online (Sandbox Code Playgroud)
作为一般规则,使用头文件来定义每个模块的接口而不是依赖模块中的ad hoc原型更好(更强大).这有时被称为SPOT(单点真相)原理.