Sunday, July 12, 2009

C++ header file question...?

In C++ if you write a function you are going to include in a separate file that use a class from the STL do you include that in the .h file, .cpp file, or both??








example:





.h file





// do i include string here in the .h file?





#include%26lt;string%26gt;





std::string foo(std::string x);








.cpp file





// or do you includ it here in the defination





#include%26lt;string%26gt;?





std::string foo(std::string x){


return x + "asdf";


};





or do you do it in both????

C++ header file question...?
You’ll need to include a header file wherever you use something from it. In your example, you definitely need to include it in the header file. Now, in your case, you don’t need to include it in the source file, but you should.





Includes cascade. That is, your source file includes it’s respective header file, the one where you declare std::string foo(…). However, that header file includes string, so… But you shouldn’t assume that a header file includes another. You should include string in both the header file and source file, because the declarations are required in both.
Reply:What a good question, the answer is just the header.





Why ? Because in this case the cpp file has already been compiled into a type of object file known as a library.





And the CRT or C RunTime library is linked into your program by default. You most likely therefore would recieve an error if you tried also including the cpp for the compiler because you would wind up with two indentical foo functions in the resulting program!





For other libraries though you have to actually mention them for the linker as well, otherwise you would recv a link error that the function is notr implemented(or worse a runtime error if you've been tricky)
Reply:You need it in the header file else std::string would be unresolved. There's a case where you may get away without it: when some other file you include in turn include it. But for documentation sake you should always explicitly include your dependencies.








Most header files have some macro trickery such as:





#ifndef __blahblahblah


...





#endif





So the header file can be included multiple times in the course of processing your .cpp file and won't run into "multiply defined" errors.

cabbage

No comments:

Post a Comment