c++ extern command

Started by
9 comments, last by Kobo 12 years, 4 months ago
Without knowing the code or the circumstances I am thinking this: Circular dependency.

d3dUtil.h needs to use those externs for various utility functions so it relies on those externs (in d3dApp.h).
d3dApp.h makes use of some of those utility functions, so it relies on d3dUtil.h.

If d3dUtil.h includes dadApp.h to use those two externs and then d3dApp.h turns around and includes d3dUtil.h to use the utility functions then you can see where it gets ugly.
Advertisement

well, that is what is confusing the hell out of me.

I'll try to make more simple example.

I have:

- A.h

- B.h

- B.cpp

B.h has : extern D3DApp* gd3dApp; Do note the EXTERN keyword.

Now, B.cpp has D3DApp* gd3dApp = 0; No extern keyword.

This, i think, i understand. In B.h, you declare an external variable, wich means, that it is define / initialized somewhere farther in the code or in other file.




But what gave me a problem, is that A.h already has the " extern D3DApp* gd3dApp", wich B.h also has. Not definition, but (Extern) declaration. B.h then includes this A.h, and as such, you call extern two times on same variables within same file (while definition is in third file - B.cpp).

So if understand Kobo correctly, you don't need to call extern command in B.h, because it includes A.h, wich already did that (as in, it already used extern command on that variable)? And B.cpp actually then defines this varible?




tnx all for help btw.


No, you need to use the extern keyword once and not declare it again. If you include a header that has extern D3DApp* gd3dApp, that is the same as putting extern D3DApp* gd3dApp in the file that has the #include directive.

if A.h declares "int x = 5;" in it, then if B.cpp includes A.h it will know x = 5. Everything you include gets put into a translation unit by the preprocessor, which is sort of like having all your text from each file you include smashed into a giant wall of text. If you want to use an external variable like gd3dApp, you declare it exactly one time in a header somewhere with the extern keyword. Putting interface in headers that get included and implementation in source files that don't get included in other source files will help you. It will start getting tricky and tempt you to include headers in headers if you are putting logic in some of your headers that might want to know more about gd3dApp than its type (D3DApp *).

You want to have "extern D3DApp* gd3dApp" in a header somewhere that gets included by source files. You do not want to declare D3DApp* gd3dApp without the extern keyword.

This topic is closed to new replies.

Advertisement