Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

How does #include work in C++?

If a library is included in a class header and then this header is included in another class do I have to include the library again?

For example:

#ifndef A_H
#define A_H

#include<someLibrary.h>

class A{
  ...
}

#endif

Then another class includes the A.h header

#include<A.h>   //include class A
class B{
   ...
}

Do I have to include the "someLibrary.h" in class B?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

No, #includes are transitive.

However, if your second file itself uses symbols from someLibrary, it's good style to re-include the header. That way you're not "hoping and praying" that you never remove the intermediate include. Your codebase will be more robust if every source file #includes everything that it directly needs. Header guards prevent this from being a wasteful policy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...