我正在尝试链接两个文件。意味着,有文件“file1.c”和“file2.c”。
文件1.c
#include"stdlib.h"
#include"stdio.h"
void function1(int a)
{
printf("hello I am file%d.c\n ", a);
}
void main()
{
function1(1);
}
文件2.c
#include"stdlib.h"
#include"stdio.h"
#include"file.h"
void function2(int b)
{
printf("hello I am file%d.c\n", b);
}
int main()
{
function2(2);
function1(1);
}
然后我制作一个头文件file.h作为
#ifndef hell
#define hell
void function1(int a);
#endif
当我将 file2.c 编译为“gcc file2.c file1.c -o file2 "它给出以下错误
/tmp/cc4tno9R.o: In function `main':
file1.c:(.text+0x24): multiple definition of `main'
/tmp/ccL4fEki.o:file2.c:(.text+0x24): first defined here
collect2: ld returned 1 exit status
头文件怎么写?头文件有没有错误? 或者 file2.c 中的错误?
那么 extern 呢?它是否用于相同目的?
最佳答案
假设目录结构是这样的:
Project
|
------------------------------
| | |
csource output header
| | |
*.c files executable .h files
files
现在,把这两个 .c files
在source
里面文件夹。
函数.c
int sum(int a, int b)
{
return (a + b);
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include <mymath.h>
int main(void)
{
int result = sum(11, 19);
printf("Result: %d\n", result);
return EXIT_SUCCESS;
}
把这个头文件放在header
里面文件夹。
mymath.h
#ifndef _MyMath_H__
#define _MyMath_H__
int sum(int, int);
#endif
编译:
首先,我们将编译function.c
文件并创建一个object file
与 .o
扩展名,如下:
C:\Mine\C\test\project>gcc -o output\function.o -c source\function.c
在 Cygwin 上:
Gagandeep Bali@LAPTOP ~/c/Mine/C/test/project
$ gcc -o output/function.o -c source/function.c
因为,function.c
不包含 main
方法,因此,我们将简单地使用 -c
选项,只创建一个 object file
.
在这里,使用-I
选项,基本上告诉编译器在哪里寻找 include 文件。因为,我们正在定义我们的 header
文件夹,因此,您可以使用 #include <mymath.h>
而不是 #include "mymath.h". Now we will compile the
main.c` 文件为:
C:\Mine\C\test\project>gcc -o output\main -I header\ -Wall source\main.c output\function.o
在 Cygwin 上:
Gagandeep Bali@LAPTOP ~/c/Mine/C/test/project
$ gcc -o output/main -I header/ -Wall source/main.c output/function.o
现在可以运行它了,比如:
C:\Mine\C\test\project>.\output\main
Result: 30
在 Cygwin 上:
Gagandeep Bali@LAPTOP ~/c/Mine/C/test/project
$ ./output/main
Result: 30
您还可以创建您可以使用的自定义函数的静态和动态库。我只知道如何创建静态库。
如果您想创建自己的静态库,只需先将所有 object files
图书馆里面。创建另一个文件夹,比如 library
以此目的。现在添加所有 .o
库中的文件,如下所示:
Gagandeep Bali@LAPTOP ~/c/Mine/C/test/project
$ ar cr library/mymathlibrary.a output/function.o
现在简单地编译程序如下:
Gagandeep Bali@LAPTOP ~/c/Mine/C/test/project
$ gcc -Wall source/main.c library/mymathlibrary.a -o output/main -I header
并如前所述运行。
关于c - 如何在C中使用头文件链接两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26828865/