Makefile 'fdopen: Bad file descriptor' error - c++

I'm making a makefile, and getting this error:
List.h:10:18: error: calling fdopen: Bad file descriptor
I have no idea why it happens.
Here's the beginning of List.h:
#ifndef List_h__
#define List_h__
#include "Data.h"
#include "general.h"
where #include "Data.h" is the 10th line. Data and then general is the order in which the dependencies are written in the makefile:
List.o: List.cpp List.h Data.h general.h
g++ List.cpp $(f)
data doesn't include anything and general includes only iostream, and no other class also includes iostream.
Here's Data.h:
#ifndef Data_h__
#define Data_h__
class Data
{
private:
public:
//default constructor
Data() {}
//destructor
virtual ~Data()=0;
/*****************************************************************************
* function name: operator<
* The Input: This Data, other Data
* The output: The operator will compare between two datas. The comparison will
* be used to create a sorted list.
*****************************************************************************/
virtual bool operator<(const Data& other) const =0;
};
Data::~Data() {}
#endif //Data_h__
I initially had the trivial implementation of Data's destructor after the =0, and I've also tried to move the trivial implementations of the constructor and destructor to a .cpp file. All of the above didn't work. Please help - I've been stuck on this makefile for hours and it's driving me crazy! Thanks!

First, check to see if you are using precompiled headers. If so delete all the precompiled headers.
If that doesn't work, then I think this may help. There is a bug in some version of g++ with including a header multiple times in a single unit.
Look at see if you are including Data.h multiple times.
Precompiled headers: look for .gch files and delete them.
Precompiled header
Often large projects have many header files that are included in every source file. The time the compiler takes to process these header files over and over again can account for nearly all of the time required to build the project. To make builds faster, GCC allows users to `precompile' a header file; then, if builds can use the precompiled header file they will be much faster.
To create a precompiled header file, simply compile it as you would any other file, if necessary using the -x option to make the driver treat it as a C or C++ header file. You will probably want to use a tool like make to keep the precompiled header up-to-date when the headers it contains change.
A precompiled header file will be searched for when #include is seen in the compilation. As it searches for the included file (see Search Path) the compiler looks for a precompiled header in each directory just before it looks for the include file in that directory. The name searched for is the name specified in the #include with `.gch' appended. If the precompiled header file can't be used, it is ignored.
For instance, if you have #include "all.h", and you have all.h.gch in the same directory as all.h, then the precompiled header file will be used if possible, and the original header will be used otherwise.

Related

Weird Behavior with gcc precompiled headers

I was having troubles getting pre-compiled headers to work, so I came up with the following minimal-working-example.
This is the header file foo.h
#include <iostream>
using namespace std;
void hello() {
cout << "Hello World" << endl;
}
I compile this as g++ -c foo.h gives me a compiled header foo.gch. I expect that when I compile the following source file that includes foo.h, it should pick the header foo.h.gch and I am good.
// test.cpp
#include <cstdio> // Swap ordering later
#include "foo.h" // ------------------
int main() {
hello();
}
But surprisingly, this does not compile using foo.h.gch, but rather uses foo.h. To verify you can compile this as g++ -H test.cpp
However, if I change the order of included header files as follows:
// test.cpp
#include "foo.h" // ------------------
#include <cstdio> // Ordering swapped
int main() {
hello();
}
Now if I compile using g++ -H test.cpp, it compiles from foo.h.gch, whew!
So I was wondering if this is a bug in GCC or are we supposed to use pre-compiled headers like that? In either case I think its useful to know..
With GCC, precompiled headers work only if they are the only header, and if they are included first (without any previous header).
This answer explains more why it is so.
See also the Precompiled headers chapter of GCC documentation, which says:
Only one precompiled header can be used in a particular compilation.
A precompiled header can't be used once the first C token is seen.
BTW, it could happen that pre-compiling some large header (notably in C++) is not worth the effort. YMMV.
In a nutshell, the precompiled header thing works thus:
When you request to create a '.pch' file, the compiler processes the source file as usual. While it does so, its internal structures (mostly, name tables and all associated data) are populated. At the end, it makes a snapshot of these internal structures and saves it to the '.pch' file.
Later, when compiling a source file that includes a header for which a '.pch' file exists, the compiler can omit the expensive processing of the header file and load the ready-for-use snapshot from the '.pch' file instead.
Obviously, this can be done without affecting the semantics only if:
the inclusion directive comes before anything else;
the compiler options are the same.
Anything that comes before the inclusion directive may:
add something to the internal data structures of the compiler;
affect the processing of the header file;
alter relations between entities described there.
Therefore, in this case, loading the snapshot of internal data structures would be wrong because there'd be no guarantee that it would leave these structures in the same state as after the normal processing of the header.
From the GCC manual pages:
A precompiled header can't be used once the first C token is seen.
So including <cstdio> in your precompiled header or including it first will work.

Get all include files of a cpp file considering preprocessor defines (fast)

I need a tool (command line, script or source code) that extracts all inlcude files that are included by a source file (recursive) with given preprocessor defines and include paths. I want to know the ones that could be found and the one that doesn't. The include files that could be found shall be recursivly parsed.
I know about the
gcc -M /-MM
cl /P
solution, but this does not work for me. The preprocessor stops as soon as it could not open a file. But at this time I don't have the correct path for that files and just want the preprocessor to skip that file and to tell me that it could not include that file
Also the cinclude2dot.pl from here is not useful, because it seems not to consider given preprocessor defines.
Very useful is the include file hierarchy finder from CodeProject. It considers the preprocessor flags and shows me all include files. Even the includes that couldn't be opened. But it is written in MFC and I would have to reimplement this for the gcc what is not such simple because a lot of WinAPI stuff is used even inside the parser.
Thus, maybe some one knows another solution.
an simple example:
main.cpp
#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <SharedClass.h>
#include "MyClass.h"
#ifdef FOO
#include <OptClass.h>
#endif
int main() {}
Right now I start the include extraction like (simplified):
.getAllIncludes main.cpp -I includepath1;includepath2 -PD FOO
and obtain:
cannot open //-> I don't care right now, it's a default header
cannot open // -> here I can extract the info that I need boost
SharedClass.h
SharedDependenyClass.h //a header that is included by SharedClass...
MyClass.h
TestClass.h //a header that is included by the MyClass header...
TestClass2.h //a header that is included by the TestClass header...
OptClass.h
and for
.getAllIncludes main.cpp -I includepath1;includepath2
I'll obtain:
cannot open //-> I don't care right now, it's a default header
cannot open // -> here I can extract the info that I need boost
SharedClass.h
SharedDependenyClass.h //a header that is included by SharedClass...
MyClass.h
TestClass.h //a header that is included by the MyClass header...
TestClass2.h //a header that is included by the TestClass header...
I know that the deafault header may also define some values. But in my case I don't need that information, because the project source code doesn't depend on any of that defines. If thus, I feed my tool with this preprocessor define...
In the end the tool works quite well. It runs recursivly over ALL necessary files and in the end I have all needed files for the project. Of course there are some small restrictions I don't want to name then all (e.g. every header of an source file name has the same name, ... ).
Using gcc -M <source_file>, the code is not compiled, it is only processed by the precompiler. And, any solution you may find needs to process the source using the precompiler, to be correct. Imagine that the source, somewhere, has the following snipset:
#ifdef USE_BOOST_SUPERLIB
# include <boost/superlib.hpp>
#endif
then without preprocessing you cannot know if <boost/superlib.hpp> is included.

Why don't I need to include library.cpp in the header?

I have a question about libraries. When I write a library I have 2 files: library.h and library.cpp.
The first one contains the prototypes of the functions and the second one contains the definitions. Well, in library.cpp I include #include "library.h", so they are connected in one way, but what happens with the header? Why don't I have to write #include "library.cpp" in the header?
When I use the library in the main file, I write #include "library.h", which includes the prototypes, but how does the compiler know where the definitions are?
Explained briefly:
(1) Your library.cpp file is sent to the preprocessor.
(2) The preprocessor reads the line #include "library.h" and goes and finds the file library.h.
(3) The contents of library.h are literally copied into the library.cpp file.
(4) The library.cpp file is compiled and linked with the main file.
Thus, all of the "prototypes" in the header are copied into the top of the implementation file. .cpp files are compiled and linked. The header files themselves are not compiled -- their contents are copied into the .cpp files.
There is a tool called linker which is responsible for link your generated object files. You should look for compilation process to understand it better.
The preprocessor pulls the header file into the CPP file, so the compiler sees the prototypes and the definitions together.
If you were to pull the CPP file into the header file, you would either send the preprocessor into an infinite loop, or by using
#ifndef __FOOBAR__
#define __FOOBAR__
(code file)
#endif
around the header AND source files you would read the file just once.
All the cpp files are compiled seperately and the code is accumulated in a big pile somewhere. The linker collects all the symbols in your code and assigns them an address within this pile. So although your file doesn't see library.cpp directly, it knows the symbols from library.h and the assigned addresses. It can then zoom directly to the required code in the big pile. Not the most technical answer I know..
It was my understanding that when you type #include "library.h" in your code the compiler is set to also load library.cpp. I was taught in school that there isn't really any way to break this connection unless you were to manually compile and link each file either using compiler commands or a makefile appropriate for the system you're using (Windows, *nix, MacOS, etc.)
You have to type #include "library.h" in the library.cpp file because that is where the function prototypes are stored. You can "cheat" and put the function prototypes in the .cpp file and just type #include "library.cpp" but this is bad practice and is generally discouraged in the programming community.

difference in including header in .cpp and .h

I have a code in which I #include<linux/videodev2.h>. There are three files:
one header file- includes: stdint.h and stdlib.h. Defines a couple of functions, a struct, say abc, and some #define macros. One of the functions is
int func(int, uint32_t, size_t, abc*);
one cpp file with a lot of methods, including definition of the functions in the .h file.
one main.cpp which has main() which has a function call to the method in the .h file (complete file below). This file is only for testing purposes.
#include "head.h"
int main() {
func(5, (uint32_t)5, (size_t)5, 0);
return 0;
}
What is see is a curious case:
If I include linux/videodev2.h only in .h file, uint32_t and other things defined in this header are not accessible by the .cpp files. (erros I get are: uint32_t was not declared in this scope, and uint32_t does not name a type, among others). This happens even if the first line of the .h file is #include<linux/videodev2.h>
If I include the videodev2 header in both the cpp files, it works only if I import it (videodev2) before the .h file.
If I use func(5, (uint32_t)5, (size_t)5, (abc*)0); in the main.cpp file, I get the error that abc is not declared in this scope.
I am compiling using the command: g++ main.cpp head.cpp
I am unable to figure out why is this. I would like to include the videodev2 header in the .h file since, it is almost certain that the code using the .h file will be dependent on it. But it seems that including it in .h file has no effect at all.
I must be honest here. This was C code which I had to convert to C++. I know that I am not conforming to the best practices and standards. But why is this behaviour seen?
Remember that the #include directive indicates to the preprocessor the contents of the specified file should be treated as if they appeared directly in the source file in place of the directive (paraphrased from MSDN).
With that in mind, it seems like you are encountering improper order of #includes and also missing #includes. My guess would be that you are not including your own header file in your .cpp files. This would explain cases one and three. Consider the following files:
// header.h
// #include <linux/videodev2.h> <-- Option 1
class A {
void func(uint32_t var);
};
// header.cpp
void A::func(uint32_t var) {
// implementation
}
// main.cpp
// #include <linux/videodev2.h> <-- Option 2
#include "header.h"
// #include <linux/videodev2.h> <-- Option 3
int main() {
// implementation; something creates an instance of A and calls func
}
Now, Option 1 is not exactly desirable; it's good practice to avoid #includes in header files because they can increase build times and create unwanted dependencies. However, it will ensure that the types header.h requires are there for it to use. The essential bit is that the contents of linux/videodev2.h have to appear before the contents of header.h, anywhere that header.h is #included.
This brings me to Option 2. Option 2 will also compile correctly, because linux/videodev2.h is included before your header, and your header relies on types defined in it. Also important is that both main.cpp and header.cpp must #include "header.h", because they reference symbols declared in it.
If you were to go with Option 3, you would get compilation errors that the type uint32_t is not defined, and the compiler would point to your header file. This is because the contents of the header file appear before the contents of linux/videodev2.h, and so the compiler does not yet understand what the type uint32_t is when it encounters it.
So, given all that, you have choices: include `linux/videodev2.h' before each include of your own header file, or include it directly in your header file. I mentioned earlier that the latter is not good practice, but for your particular case, it might be the better option of the two, in case your header file needs to be included in many .cpps.
I think this would be a good opportunity to dive into precompiled headers, but I'm not as well-versed in them, so I'd leave it to someone who has more experience to explain them.
Hope this helps :)
Found the answer. There was .h.gch file in the directory. I didn't know about precompiled header. Thanks ktodisco for the insight. I still have no idea why that file was there in the first place.

dealing with includes and using headers

I have "Hello World" code that uses function fhi from another hi.cpp file that has it's header.
Correct my if my understanding is wrong according following:
I can do include cpp file like #include "c:\c\hi.cpp" instead of using header without any problems except that fact that it looks more readable in header file.
If I include header like sample in my main program hi.h, must hi.h include hi.cpp, or it is done automatically according the same file name hi. I'm wondering how compiler knows where is function fhi body.
Is it possible to have different names for header and cpp files?
Programm:
#include "stdafx.h"
#include "c:\c\hi.h"
int _tmain(int argc, _TCHAR* argv[])
{
fhi(1);
return 0;
}
hi.h
#include <cstdlib>
#include <iostream>
int var;
int fhi(int f);
hi.cpp
#include <cstdlib>
#include <iostream>
int fhi(int f)
{
return 0;
}
must hi.h include hi.cpp
No. hi.h contains only declarations, that can be other by other .cpp files.
I'm wondering how compiler knows where is function fhi body.
It doesn't. You need to compile all *.cpp files into the object files. In your case, you will have two object files: program.o and hi.o. The linker can now take these two object files, and spit out the executable. References to other functions(in this case the actual definition of fhi(..)) is resolved in this stage.
Also why are you using absolute paths in #includes? It will break when you move the "c" directory around.
What normally happens is that the build system compiles the .cpp files into object files, that then are used to build the main executable. The means to tell this to the build system vary greatly.
One important point is that your hi.cpp must include hi.h. You should also put an include guard in hi.h, to make it safe to be included more than once in a translation unit.
I can do include cpp file like #include "c:\c\hi.cpp" instead of using
header without any problems except that fact that it looks more
readable in header file.
yes, you can do so but it is not recommended, one of the problems is encapsulation; you are not hiding implementation details. readability as you mention is also a concern, a header is easier to read since it clearly shows what methods are public.
If I include header like sample in my main program hi.h, must hi.h
include hi.cpp, or it is done automatically according the same file
name hi. I'm wondering how compiler knows where is function fhi body.
the header needs to be explicitly included in hi.cpp and any .cpp file that use the class defined in the header.
Is it possible to have different names for header and cpp files?
yes but it is not recommended, it makes it more difficult to find things.
as a general rule: think about that other programmers may want to look in your code so you need to structure it so that it is easy to read and understand as well as making it easier for you 2 years down the road to remember where things are.
In Visual Studio all CPP files included in the project will be compiled to produce OBJ files. These OBJ files will be linked together to form the EXE or DLL.
Including files are similar to pasting the contents of the file at that location. The only difference is that this pasting is done by the pre-compiler during compilation.
Finding out where a function body resides is done by the either the compiler if the function is inline or by the linker when the final binary is created.
First, if the header file is in the same directory as the source file including it, you can use just
#include "hi.h"
In other words, you don't have to use a full path. (See e.g. the inclusion of "stdafx.h".)
Second, in your header file you don't need to include other header files, unless you need types from those. In your header file you don't have anything that needed from the header files you include.
Third, you should protect header files header files from being included more than once in the same source file, this can be done with a so called include guard, on in some compiler via a special directive called #pragma once.
Fourth, in your header file you define a global variable var. This variable will then be defined in every source file you include the header file in, which will lead to errors. You need to declare the variable as extern:
extern int var;
Then in one source file you define the variable like you do now.
Fifth, you should never include source files in header file (with some special exceptions that you don't have to think about yet). Instead you add all source files to the project (I assume you are in MS VisualStudio) and it they will all be built and linked together automatically.
Sixth, since you seem to be using VisualC++, then you are probably using something called precompiled headers. This is something the compiler uses to speed up compilation. However, for this to work you have to include "stdafx.h" in all source files. That include actually has to be the first non-comment line in each source file.