I am working on porting some source code to a linux system, and as expected, some stuff is broken. One thing that is throwing an error for me right now, is that someone has a .h and a .cpp file that both use fclose()
The compiler is complaining about fclose() being undeclared in the header file.
here was the function declaration in the header file:
void closeFile() { if (fp) fclose(fp); }
Now, I think this is bad style, but also - how did they get this working before? Did their version of the compiler allow this kind of behavior?
Should I fix this by including stdio in the header, or move the whole thing to the cpp?
It's not bad style, you can put source code in header files, and some times you're forced to, in particular:
When defining a template class/function.
When defining an inline function.
Anyway you shouldn't put a free (defined outside a class scope) non-inline function in a header file, since that would be compiled any time a source file include such header (and this will give you a linking error).
If you're getting an error that states fclose hasn't been declared, it's probably because cstdio (or stdio.h) wasn't declared before that piece of code. Put an #include <cstdio> at the beginning of the header file.
Just to add 2 things about the other answers, remember inline is not an order, is more a guess of what the compiler should do, unless you force inline. Most compilers can decide when to inline a function, even if you did not declare it inline. It's not a must, it is a should.
Sometimes you really need to include such function/structs/classes definitions in the header, and sometimes they are not trivial or that simple. But those definitions are usually some auxiliar functions you need and you just don't want to include them on the main file, just to organize things better.
The best examples I ever seen (ok, and I didn't see those many) about this practice is game source code (that's my main interest :) ).
By the way, I usually do not put any declaration on header files (except structs and enums), I put them on separated files, unless if:
There are only a few declarations/aux functions to be made; or
These declarations are functions that I will use in another contex (of the same project, in the case) and I just think it's better to treat them as a separated 'auxiliar library' (within the same context).
Hope it helps somewhat.
Keep in mind that header files aren't compiled by themselves (usually). They are #included into source files and the definitions available when the header file is parsed are whatever was included in the source file above the header file in question.
Regardless of whether the header file is an appropriate place for the implementation of closeFile(), your header file should #include everything it needs at the top of itself. So, add #include <stdio.h> at the top of the header file.
(Note that if this is code intended to be compiled into the Linux kernel itself, you may need a different header than stdio.h. Often application-level headers aren't suitable to be used in the kernel sources.)
fclose() will be undefined if you haven't included stdio.h either in this header or before it everywhere this header is used. That is why the error occurs.
I personally see nothing wrong with the code being allowed to be in a header file, however, if it is, and you're using C99, you should declare it
inline void closeFile() { if (fp) fclose(fp); }
This means multiple compiled objects won't have closeFile() symbols (because of inline) and the inline hints to the compiler that this shouldn't be left as a function call but substituted inline which is probably want you want for speed.
The headers are included by textual substitutions (that is the whole content of the header is substituted to the #include declaration). So if there is only one .cpp file that include this particular header, this is equivalent with having the function defined in the .cpp file. I think this is the reason why it was working (at link time).
The C standard only define the header that must be included to have a function available but does not forbid the system header to include one another. So it is possible that on some system, the stdio.h header was implicitly included by another header (and thus no error reported by the compiler).
Personally, I would move such code to the .cpp file, as it will be less brittle (the header can be included by multiple .cpp files, the header will not require a previous inclusion of the stdio.h header) and will allow for quicker recompilation if the implementation must be changed (to add logging or proper error handling, as closing a file can fail).
Related
Please refer to the first answer in this question about implementing templates.
Specifically, take note of this quote
A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.
I bolded the part that I'm most interested in.
What's the significance of a .tpp file? I tried doing exactly what was suggested in that page and it worked. But then, I changed the file extension to any random gibberish (like .zz or .ypp) and it still worked! Is it supposed to work? Does it matter if it's .tpp or any other extension? And why not use a .cpp?
Here's another thing I'm confused about.
If my implementations were written in a .cpp and the header defined non-templated functions, then I'd only need to compile the .cpp file once, right? at least until I changed something in the .cpp file.
But if I have a header defining templated functions and my implementations are in a file with a random funky extension, how is it compiled? And are the implementations compiled every time I compile whatever source code #includes said header?
Does it matter if it's .tpp or any other extension? And why not use a .cpp?
It does not matter what the extension is, but don't use .cpp because it goes against conventions (it will still work, but don't do it; .cpp files are generally source files). Other than that it's a matter of what your codebase uses. For example I (and the Boost codebase) use .ipp for this purpose.
What's the significance of a .tpp file?
It's used when you don't want the file that contains the interface of a module to contain all the gory implementation details. But you cannot write the implementation in a .cpp file because it's a template. So you do the best you can (not considering explicit instantiations and the like). For example
Something.hpp
#pragma once
namespace space {
template <typename Type>
class Something {
public:
void some_interface();
};
} // namespace space
#include "Something.ipp"
Something.ipp
#pragma once
namespace space {
template <typename Type>
void Something<Type>::some_interface() {
// the implementation
}
} // namespace space
I thought the whole point of writing definitions in headers and the implementations in a separate file is to save compilation time, so that you compile the implementations only once until you make some changes
You can't split up general template code into an implementation file. You need the full code visible in order to use the template, that's why you need to put everything in the header file. For more see Why can templates only be implemented in the header file?
But if the implementation file has some funky looking file extension, how does that work in terms of compiling? Is it as efficient as if the implementations were in a cpp?
You don't compile the .tpp, .ipp, -inl.h, etc files. They are just like header files, except that they are only included by other header files. You only compile source (.cpp, .cc) files.
Files extensions are meaningless to the preprocessor; there's nothing sacred about .h either. It's just convention, so other programmers know and understand what the file contains.
The preprocessor will allow you to include any file into any translation unit (it's a very blunt tool). Extensions like that just help clarify what should be included where.
Does it matter if it's .tpp or any other extension? And why not use a .cpp?
It doesn't matter much which extension is actually used, as long it is different from any of the standard extensions used for C++ translation units.
The reasoning is to have a different file extension as they are usually detected by any C++ build systems for translation units (.cpp, .cc, ...). Because translating these as a source file would fail. They have to be #included by the corresponding header file containing the template declarations.
But if the implementation file has some funky looking file extension, how does that work in terms of compiling?
It needs to be #included to be compiled as mentioned.
Is it as efficient as if the implementations were in a cpp?
Well, not a 100% as efficient regarding compile time like a pure object file generated from a translation unit. It will be compiled again, as soon the header containing the #include statement changes.
And are the implementations compiled every time I compile whatever source code #includes said header?
Yes, they are.
The file extensions of header files do not matter in C++, even though standard source-file extensions such as .cpp should be avoided.
However, there are established conventions. These help human programmers navigate the code. Calling template implementation files .tpp is one of such conventions.
Something nobody has mentioned yet is that some external tools might rely on such conventions.
For instance, I routinely employ a popular grep substitute which allows searching only in files of a given type. This program will recognize .tpp files as C++, but not, say, .zz files
(My apology if this question sounds familiar, but I was really confused. And I could not comment under existing questions. )
I browsed a few questions, this, whose answer says:
If ...(defined a function in header), and then include the header into two or more different source files, you'll have multiple definitions of the same function.
But I thought the book taught us to always wrote definition guard inside headers. With the guard, we won't have multiple definitions, right?
I tried to find the reason in book , but with not much help: it says the reason (why function is declared in header file, and defined in source file) is the same reason as variables (in a previous chapter). And when I jump to that previous chapter, there is no explicit explanation.
why declare a function in header but define it in source file?
The declaration is needed to call the function. It goes in the header so that any file which wants to call the function can include the header and have the declaration available.
There can only be one definition, so it goes in just one source file.
With the guard, we won't have multiple definitions, right?
There would be one definition in each source file that included the header. The guard prevents multiple inclusions from the same source file, but not inclusions from different source files.
But I thought the book taught us to always wrote definition guard inside headers.
Definition guard prevents a header to be included multiple times in one C file. It does not prevent a header from being included in multiple C files.
With the guard, we won't have multiple definitions, right?
If you put the definition in a header, and include that header in multiple C files, then you would end up with multiple definitions of the same function.
Having multiple definitions of a function or a variable will cause an error at linkage time, unless the function or the variable is static. In case of a static function / variable you would end up with multiple copies of that function / variable, which is not usually the desired outcome.
With the guard, we won't have multiple definitions, right?
Not right. Include guards ensure that when a source file is compiled, the header won't be processed twice. But when you have several source files, each file is compiled separately, so include guards do not stop multiple definitions.
That's not the same thing, using a definition guard doesn't prevent one implementation from spanning multiple source files, it prevents the same declaration from being included more than once in the same file (which would cause compilation errors indeed).
So a guard is useless against a function defined directly in the header, since its implementation will be then included in multiple source files and, unless the compiler chooses to inline it, it will be present more than once. Placing the implementation in the source file will make the function being compiled in its own translation unit, and any call to it will be resolved accordingly.
Actually the compiler could inline even functions implemented in the source file so this could not happen.
A declaration goes in the header.
A definition goes in the body.
The header guard is to prevent multiple declarations at compile time, while compiling a single unit that may include the same header more than once (via other The definition goes in the body to prevent multiple compiled versions of the definition in multiple objects that included it colliding at link time.
Edit to answer comment because I can't format a comment:
It's not OK to define the same thing twice.
It is not OK to declare the same thing twice.
It is OK to pre-declare the same thing twice.
// predeclare:
class thingy;
// declare:
class thingy { int x(); };
// define:
thingy::x() { return 1; }
Anything you put in a header is likely to appear twice when compiling a single file because headers often get included by other headers, so they get included more than once. Header guards prevent this at compile time.
Anything you put in a header which defines something is likely to end up being defined in the compilation of more than one file if they both include the header, and then appear twice at link time. Header guards cannot prevent this, hence we avoid defining things in headers.
You can think of the #include in C++ as a giant macro - it means "grab an entire file and shove it into my source code at this point, before you compile it".
Do stand alone C++ functions need a header file and a code file?
I am writing some C++ functions that use some of my other C++ classes but don't belong in a class themselves. They are intended to be compiled in a dll and so I was wondering if it was necessary to declare them in a separate header file or if I could/should just put the declarations in the .cc file.
Maybe this would just be bad practice?
The header file is useful because it is able to let other source files know about the functions that are declared in a different translation unit.
This is necessary by the compiler to be able to check that what you are invoking is correct for the type checker. But the necessity comes from the declaration itself not from the existence of the header file.
For a DLL, if I remember correctly, you are not forced to do it just because you are going to declare the signature of the function anyway whenever you are using them, eg.
extern C __declspec(dllimport) void foo();
Of course this means that you will need to forward declare them anyway so I don't see any problem in having an header files for your DLL, it will just keep all signatures together.
It is not strictly necessary, but it is strongly recommended.
Place the function declarations in a header file and the function definitions in a source (.cc) file. The motivation is to allow the users (here, fellow programmers) to view only the interface but not the implementation (since it can change). Moreover, it allows other source files to include your header file and use the functions provided by you.
The only exception are static functions, they should not be declared in a header file because they are not supposed to be viewed or used outside your source file..
If you are going to use a function outside of the source file in which it's defined, you absolutely need a declaration. It is best to put the declaration in a header file so that it's consistent, otherwise you just end up repeating yourself and introducing a potential source of bugs.
What is happening when you include some file and what is happening when you forward declare some function/class? If two files include the same file will the first one success to read all the function the second will fail but still be able to use the functions??
What happens when I forward declare some function? Is this function now "saved" and I can use it anywhere or it's known only for the same file? then why two files with include(to a file with guards) will work?
Can I just include every thing in the main and won't bother any longer?
EDIT:
And why the cpp files should include their headers?? What If i won't include them?
What is happening when you include some file and what is happening when you forward declare some function/class?
When you include a file, its contents get "copy and pasted" into the inclusion source by the preprocessor. When you forward declare a function/class you are declaring an incomplete type, letting the rest of the translation unit know that a function/class with that name exist and making it usable within context where an incomplete declaration is allowed.
If two files include the same file will the first one success to read all the function the second will fail but still be able to use the functions??
If the included file includes proper include guards, the second inclusion within the same translation unit will be effectively a no-op. If two different source files include that same header file, the full content will be included in both files.
What happens when I forward declare some function? Is this function now "saved" and I can use it anywhere or it's known only for the same file? then why two files with include(to a file with guards) will work?
The function can only be used within the translation unit that contains the forward declaration. Generally each source file (.cpp) is a different translation unit, macro definitions (those of the header guards) as well as declarations/definitions are valid within that translation unit. Header guards prevent the same header file from being included more than once within the same translation unit, to prevent multiple declaration errors.
What is happening when you include some file and what is happening
when you forward declare some function/class?
When you include a file, the preprocessor effectively copy pastes the entire included file into the file doing the includeing. When you forward declare a function/class, you're telling the compiler that it exists, but you don't need the entire header file. This is required when you have circular dependancies, and and greatly reduce compile times in other places.
If two files include the same file will the first one success to read
all the function the second will fail but still be able to use the
functions??
If the same file gets included twice in one translation unit (.cpp file), then the both will "succeed", but if the header has include guards of any sort, nothing will be loaded the second time, because the preprocessor has already "copied" it into the translation unit, and to do it a second time would make duplicates of everything, which would be a bug. So all files involved can use all the functions in all the headers included up to that point.
What happens when I forward declare some function? Is this function
now "saved" and I can use it anywhere or it's known only for the same
file? then why two files with include(to a file with guards) will work?
Yes, if you forward declare a function/class in a header, it can be used by any other file that includes that header.
Can I just include every thing in the main and won't bother any longer?
Probably. Once you get to more complicated examples, you'll end up with circular dependancies, which require certain things to be declared and/or defined in a certain order. Other than that, yes. You can include everything in main and keep it simple. However, your code will take FOREVER to compile.
And why the cpp files should include their headers?? What If i won't include them?
Then that .cpp file won't know that anything else exists outside of itself. Not very useful.
Short answer:
Forwarding a class/function allows the compiler to not actually have to compile the entire class/function unless needed.
Long answer:
Forwarding a class/function is just like declaring a class/function without defining it. You're promising to define it later, but for now you just want to inform the compiler it exists. You usually do these forward decelerations in header files. This generally results in faster compile times because in .cpp files that include your header, only those that actually need the class you've forwarded and include it's appropriate header file need to actually compile that included class's code.
I have a very simple class and I'd like to consolidate it to a single .h file. Will everything work the same if I cut and paste the guts of my .cpp to the bottom of my .h?
In particular, there are static member variable initializations int MyClass::myStaticVar = 0; outside of any class definition at the top of the .cpp, and following that, there are static member function implementations void MyClass::myStaticMethod() {...}. Some non-static member functions are already being implemented in the .h, not the .cpp. So you can see there are some nuances here that I'd like to clarify.
Edit So far, what I'm getting is:
This is naughty, but it will work if you only #include the .h once.
It breaks the convention and doesn't really work like a .h so it might
as well be named .doofus.
Now, for example, look at the TUIO C++ bindings. A lot of the classes consist of one .h file, no cpp (TuioPoint.h, TuioCursor.h, TuioObject.h, etc). I don't think this is so bad...
If you're left with a single cpp file in the entire project, then it will work (but it's bad practice). If you have two cpp files that both include that header, you're breaking the one definition rule, and you (should) get linker errors.
You can do this if (A) All the functions are templates (in fact, you must in this case), or (B) all the functions are marked as inline.
[Edit]
The reason you aren't already having problems is a function defined in the class definition is automatically marked as inline. Thus: no problems. However, if the function is defined outside of the class definition, it should be in a cpp file. Also, static members should always be in a cpp file.
[Edit2] The reason non-inline, non-template functions and File scope varaibles (globals and static members) should always be in a cpp file, is that when the compiler finds that line of code, it creates the function/variable right there. Obviously, it must be created once to be used. Why not in a header file? Because then if the header is included in two cpp files, it will be created in two places (I have hpp files at work that are literally included in several thousand cpp files). C++ has a "one-definition rule" where each function/object can only be defined/created once, to prevent this obvious error:
int MyClass::myStaticVar = 0;
int MyClass::myStaticVar = 7;
Which would it use? You've just created two variables with the same name! So this isn't allowed, even if they were exactly the same, (except for inline/template). Each cpp file is compiled once and only once (unless for some oddball reason it's included from something else), which prevents accidental violations of the one-definition rule.
Also, hpp files are for declarations, and cpp files are for definitions/instantiations.
what good would the .h file be anymore? you can't have multiple .cpp files #include this .h file. And if this .h is only included by a single .cpp, then why do you need the .h file in the first place - just put everything in the .cpp.
In addition to Mooings answer you might want to consider the compile/link process for a while.
The compiler compiles the .cpp files, not the .h files (by convention).
This has the consequence that for each .cpp file you need the definitions for the classes you reference in order to create instructions for the code in the .cpp. The .h files provides that.
What you do not want is identical pieces of code being duplicated across your program, which would be the consequence of compiling .cpp files including headers with implementations(what you are suggesting); hence the one definition rule.
In a one .cpp-file project as Mooing suggests you can of course abuse this to your delight as long as you have a .cpp with a main and only one set of includes.
Essentially, this is what #include does (it pastes the header into the cpp, basically doing the same thing in a sense). So, yes, everything SHOULD work out fine, assuming no odd cases. I can't see why you would want to do this though. You'd be better off just flat out defining the functions and such in the class definition or just using #include. Is there any reason you're choosing not to?
EDIT: In response to your edits, why are you implementing members in the header? I'd suggest moving those to the .cpp unless this is a template class or some similar special case. Use the header for prototype and decleration, use the cpp for definition. That should solve any issues for you.