sharing a function between 2 .c files

假如想象 提交于 2019-12-20 07:47:17

问题


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


回答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:


including the .h files is not enough because it only includes the prototype of that function not the definition of the function and the definition of the function is in a seperate .c file.

one way to fix it is just type:

gcc -o out file1.c file2.c

or as Nate says you could seperate the compilation process and the link process




回答3:


Now, if I want to access a function defined (in) file1.c in file2.c

A function defined in FILE1.c Access from FILE2.c example function: void sync(all){start sync ...}

Need on File2.h

include File1.h

AND Need on File2.c

include File1.h

Nothing else!

I always use also the keyword EXTERN in File2.h

Example:

extern void sync(all);

The voted also work, choose with what you feel better, I feel better when I saw what happend during coding. Imagine an other team member has to review your code, it will be harder...



来源:https://stackoverflow.com/questions/7773778/sharing-a-function-between-2-c-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!