Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

linker - C++ extern keyword on functions. Why no just include the header file?

If I understand it correctly this means

extern void foo();

that the function foo is declared in another translation unit.

1) Why not just #include the header in which this function is declared?

2) How does the linker know where to look for function at linking time?

edit: Maybe I should clarify that the above declaration is then followed by using the function

foo();

It is never defined in this translation unit.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

1) It may not have a header file. But yes, in general, for large projects, you should have a header file if multiple translation units are going to use that function (don't repeat yourself).

2) The linker searches through all the object files and libraries it was told about to find functions and other symbols.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...