Does every .h file have a corresponding object file?

若如初见. 提交于 2019-12-24 08:58:04

问题


I'm trying to write a makefile, but I don't really understand how object files work. There are no .o files in my folder, so how can I be compiling them? Does every .h file have a corresponding .o? If not, then how do we know if we have to compile an object file or not? Sorry if these are stupid questions, I'm new to programming.

Thank you.


回答1:


Basically the header (.h) files tell the compiler that things exist when it's generating the object (.o) files. The compiler generates object files from source (.c/.cpp/etc.) files. If the compiler doesn't know specifically about something, it assumes the header was right and leaves a "name" behind for the linker.

The linker will take the object files and generate an executable by replacing "names" in the object code with code from other object files.

This is a very high level overview of what happens. There are many many pages on the specifics.




回答2:


A simple answer to illustrate the overall concept:

Every .c file contains program code which is translated by the compiler into an .o file containing the machine code.

Usually different .c files are combined to one software. But then they must somehow be connected. Hence their .o files must be connected to an executable. This is what the linker does.

The .h files describe connection points of .c files.

The linker uses the .c file connections to produce the software.

This is a simplification, however:

For example, the .h files are not consulted by the linker. They merely serve the compiler to tell him that a certain symbol is a connection point the linker must resolve.

The .h files are for conveniance of the software developper. When a .c file has "connection points" for the linker its peer .h file may list them all. If another .c file wants to use them it may just include the corresponding .h file. But this is just a convention. Theoretically, only the .c files are essential. In theory every software project could be written with .c files only (however, mostly not in due time).



来源:https://stackoverflow.com/questions/49542064/does-every-h-file-have-a-corresponding-object-file

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