Organization of C files

后端 未结 8 1672
悲哀的现实
悲哀的现实 2020-12-13 13:30

I\'m used to doing all my coding in one C file. However, I\'m working on a project large enough that it becomes impractical to do so. I\'ve been #including them together but

8条回答
  •  一向
    一向 (楼主)
    2020-12-13 14:33

    Compiler

    You can see an example of a C 'module' at this topic - Note that there are two files - the header tea.h, and the code tea.c. You declare all the public defines, variables, and function prototypes that you want other programs to access in the header. In your main project you'll #include and that code can now access the functions and variables of the tea module that are mentioned in the header.

    It gets a little more complex after that. If you're using Visual Studio and many other IDEs that manage your build for you, then ignore this part - they take care of compiling and linking objects.

    Linker

    When you compile two separate C files the compiler produces individual object files - so main.c becomes main.o, and tea.c becomes tea.o. The linker's job is to look at all the object files (your main.o and tea.o), and match up the references - so when you call a tea function in main, the linker modifies that call so it actually does call the right function in tea. The linker produces the executable file.

    There is a great tutorial that goes into more depth on this subject, including scope and other issue you'll run into.

    Good luck!

    -Adam

提交回复
热议问题