分享2 .c文件之间的函数 [英] sharing a function between 2 .c files

查看:114
本文介绍了分享2 .c文件之间的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DIR1 DIR2有,在file1.c和file1.h。

DIR2有file2.c中

现在,如果我想访问在file2.c中file1.c中定义的函数,我需要声明它file1.h,包括在file2.c中file1.h - 是一个有效的假设

如果没有,请解释。

如果是,即使在这样做,我收到未定义参考运作的错误。


  

file2.c中:29:未定义引用'功能'
  collect2:劳工处返回1退出状态
  的 * 的错误code 1



解决方案

编译C程序分为两个步骤基本步骤发生:编译和链接。编译源变成code到对象code和链接对象看跌期权code一起,并联系所有的符号在一起。

您的问题是连接问题,而不是一个编译器的问题。

您很可能是在以下几点:

  GCC DIR_2 / file2.c中

相反,做到以下几点:

 的gcc -c DIR_2 / file2.c中
GCC -c file1.c中
GCC -o出来file1.o file2.o

原因出现这种情况是不是因为你没有在头声明功能,或者没有正确包括头。当链接器试图把所有的符号一起在可执行文件,它无法找到你的功能,因为你只是链接的你一半的程序

dir1 has dir2, file1.c and file1.h.

dir2 has file2.c

Now, if I want to access a function defined in file1.c in file2.c, I need to declare it in file1.h and include file1.h in file2.c -- is that a valid assumption?

If no, please explain.

If yes, even after doing that I am getting "undefined reference to function" error.

file2.c:29: undefined reference to `function' collect2: ld returned 1 exit status * Error code 1

解决方案

Compiling a c program happens in two steps basic steps: compiling and linking. Compiling turns source code into object code, and linking puts object code together, and ties all of the symbols together.

Your problem is a linker problem, not a compiler problem.

You are likely running the following:

gcc dir_2/file2.c

instead, do the following:

gcc -c dir_2/file2.c
gcc -c file1.c
gcc -o out file1.o file2.o

The reason this happens isn't because you didn't declare the function in the header, or didn't include the header properly. When the linker tries to put all the symbols together in the executable, it can't find your function because you are only linking half of your program.

这篇关于分享2 .c文件之间的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆