sharing a function between 2 .c files

前端 未结 3 1108
无人共我
无人共我 2021-01-29 10:24

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 inclu

3条回答
  •  [愿得一人]
    2021-01-29 11:26

    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.

提交回复
热议问题