I build DLL that contains external object from 3rd party DLL with
my3rdObject->EOF()
function
But my main DLL depends from <stdio.h> lib that contains this define
#define EOF (-1)
therefore, when compiling, an error occurs
error C2059: syntax error: '('
How to solve the problem?
enter image description here
This is really bad code.
But you could workaround it by surrounding your code calling the EOF method with an #undef and #define block.
Example:
#include <My3rdObject.hpp>
#include <stdio.h>
#undef EOF
int foo()
{
My3rdObject* my3rdObject = new My3rdObject();
my3rdObject->EOF();
delete my3rdObject;
}
#define EOF (-1)
I highly recommend writing an anti corruption layer. This is simply the kind of code you don't want in your codebase.
Preferred solution: don't use stdio.h. Upgrade your C++ code from I/O in the C style to I/O in the C++ style. However, for a workaround keep reading.
But my main DLL depends from <stdio.h> lib
No, it does not. Binary files, such as DLLs, have no dependence on source files, such as headers. Rather, the code for your DLL depends on the stdio.h header. More precisely, the particular source file in question uses that header.
So move the problem to another source file.
This is not sweeping the problem under the rug, but taking advantage of modularization. Create a new source file and a new header that for now will implement a single function. The header might look like the following.
#ifndef INCLUDE_GUARD_FOR_THIS_HEADER
#define INCLUDE_GUARD_FOR_THIS_HEADER
// Make sure the class in question is declared.
// Ideally, you would use a header from the third-party library, but avoid a header
// that declares the EOF member function.
class ThirdObject;
// Declare a function to wrap EOF().
// (Drop the `const` if EOF was not declared as a const member.)
int check_eof(const ThirdObject & to_check);
#endif // INCLUDE_GUARD_FOR_THIS_HEADER
This header can be included without inteference from stdio.h. The corresponding source file would also avoid interference by not including stdio.h. As long as you don't have a macro definition of EOF available in this source file, there is no problem.
#include "the_above_header.h"
#include <ThirdParty>
int check_eof(const ThirdObject & to_check)
{
return to_check.EOF();
}
Keep in mind that this function takes a reference, while the code in the question implies a pointer is being used. So the code from the question would become
check_eof(*my3rdObject);
Problem solved by rename "EOF" method to "EOF1" in *.idl file !
Details here: https://imgur.com/a/95wJsQE
Thanks to everyone who responded and helped!
Related
For example in foo.h:
typedef struct foo_t foo_t;
/* Lots of function declarations dealing with foo_t... */
int foo_print(const foo_t *foo); /* Print foo to stdout. */
int foo_fprint(FILE *f, const foo_t *foo); /* Print foo to file f. */
I don't want to litter foo.h with too many other header files that users of foo.h might not have wanted to include, but I do need to declare functions that take types such as FILE*. I doubt that I am the first to encounter this dilemma, so what do people usually do in these circumstances? Or am I misguided in wanting to avoid including stdio.h in my header files?
EDIT:
People seem not to be understanding my question. To clarify, here are some potential solutions:
Just include stdio.h and not worry about it causing conflicts in my clients' code (such as if they happened to have their own function that happened to be called getchar).
Use an #ifdef to find out if stdio.h had already been included, and only then declare the FILE*-related functions. The downside of this is that it would impose a particular ordering to #includes in my clients' code.
Move all I/O-related declarations to a separate header file such as foo_io.h.
What question is what is the best thing to do?
Short answer: you are trying to solve a non-existing problem.
If you use FILE, you include stdio.h or cstdio in C++. It's that simple.
Trying to "optimize" #includes, besides obvious cases of unused ones, will not buy you anything and cause problems.
You should strive to have header files compile cleanly in an empty source module. For example:
#include "myheader.h"
and that's it. If you put that in a C++ source file and compiled it with no other code, you should get no compiler errors.
If you do get errors, then you need to justify why there are errors. The only legitimate reason I would think of for errors is that the header is internal in your library, and was not meant to be used standalone by the user of your library.
If the header is supposed to be used by your clients, do not "fix" the problem by taking the test source file above and adding headers to the source. You fix it by including the proper headers within (in my simple case) myheader.h
Refering to the updated question:
Conditionally enabling or disabling blocks of code (or features) depending on order of included files stinks as hell. It's a straight way to hell.
If you want to enable or disable your functionality, making your code more modular, you can use preprocessor macros, possibly requiring user to explicitly choose compilation mode.
#ifdef USE_STDIO
#include <stdio.h>
#endif
lotsa lotsa code
#ifdef USE_STDIO
int foo_print(const foo_t *foo);
int foo_fprint(FILE *f, const foo_t *foo);
#endif
Downside of this solution: code becomes harder to follow.
Second option is to extract those methods to foo_io.h (and possibly foo_io.c). The downside of this solution is that you're forcing user to include two files instead of one.
You've already answered your own question. Both 1) and 3) are valid solutions. If you use FILE* in one of your functions then it only makes sense to use your function in combination with the header where FILE is declared. As others noted, there is no header that would forward declare FILE, so your only choice is to include stdio.h.
If your client includes your header file, assume that all the functions will be used. Do not use conditional compilation for cutting out include's. If I'd include your header file and see that that it contains a declaration of a function that uses FILE* I would expect to have stdio.h included as well.
If you're using a standard library functionality, just include that standard header full stop. Don't try to over-think that someone may have a function with the same name as something in the standard library: Their code is already fragile/broker and you shouldn't worry about such cases.
I can't make out if your code is C++ or C though (note that even though C++ may have roots in C they are distinct languages). If it's C++ you can use cstdio instead of stdio.h and use features from the std namespace instead of the global namespace. Otherwise if your code is C you have to use stdio.h
I'm learning C++ and I'm at a fairly low level still. - I'm currently looking at using header files and I have a two part question.
Part 1
As I understand them so far, header file definitions are similar to hard coded strings within VB.net? For example I can do the following #define STOCK_QUANTITY 300 and then reference my definition when using it within functions? I assume this works the same way as VB.net strings as I only need to change the value in one place should I need to make changes to the definition and my program references the number 300 on a few hundred different lines?
Part 2
Now, as I said I'm still learning so I'm still doing ye old multiplication tasks. I'm good within using functions with my main .cpp file but I'm not moving on to header files. This is my code snippet thus far.
add.h
#ifndef ADD_H
#define ADD_H
int add(int x, int y);
#endif
main.cpp
#include "stdafx.h"
#include <iostream>
#include "add.h"
int main()
{
using namespace std;
cout << add(3, 4) << endl;
return 0;
}
When trying to run this I receive 2 build errors and it will not compile.
Apologies is these are silly questions, but I would appreciate insight, tips or even some other things I should consider. Thanks.
EDIT
Based on an answer I've changed my add.h too
#ifndef ADD_H
#define ADD_H
int add(int x, int y)
{
return x + y;
}
#endif
As soon as I read the answer I realised I hadn't even told the function what to do :( - Gosh.
You have not added a function body for the function add
int add(int x, int y)
{
// add stuff here
}
This can be done in either the header file, or a seperate cpp file for add. You are trying to call the function that has no code. This is known as a function prototype.
You have only declared that the function add exists, which is why you can call it. But you don't actually define the function anywhere.
In C++ you have to differ between declaration and definition. Sometimes those are done at the same time, like when declaring a local variable. Other times you separate them, like when having a function prototype in a header file (like you do) then that's the declaration. The definition of the function is then the implementation of the function.
After the edit, you now have another problem. And that is if you include the header file in multiple source files, each of those source files (formally known as translation units) will have the function defined and you will get an error because of that.
It can be solved by making the function static or inline. Or better yet, create a new source file (like add.cpp) where you have the definition of the add function, and keep only the declaration (prototype) in the header file.
As for part 1 of your question:
While #defines do as you described, there are some of disadvantages with using them (e.g. They are parsed by the pre-processor, and not by the compiler so no type checking, and also you can get funky errors if you have slightly more complicated macros.
So while your statement is valid, in that it defines a global constant that you only need to modify in one place, and can use in multiple places, for that purpose it is better to have an actual constant variable in the header file:
e.g.
const int STOCK_QUANTITY = 300;
Now you explicitly name it an integer, and also the compiler can perform extra checking.
See also Item 3 in Effective C++ by Scott Meyer (which is a must read in my opinion if you are serious about contineouing programming in c++, although you need allready some experience before reading that.)
Being pretty new to C++, I don't quite understand some instructions I encounter such as:
#ifndef BOT_H_
#define BOT_H_
#include "State.h"
/*
This struct represents your bot in the game of Ants
*/
struct Bot
{
State state;
Bot();
void playGame(); //plays a single game of Ants
void makeMoves(); //makes moves for a single turn
void endTurn(); //indicates to the engine that it has made its moves
};
#endif //BOT_H_
What I don't understand is the "#ifndef BOT_H_" and the "#define -- #endif"
From what I gather, it defines a constant BOT_H_ if it's not already defined when the precompiler looks at it. I don't actually get how the struct inside it is a constant and how it is going to let me access the functions inside it.
I also don't see why we're doing it this way? I used C++ a while back and I wasn't using .h files, so it might be something easy I'm missing.
This is known as an include guard, to prevent the contents of a header file from being #included more than once.
That is, it prevents the contents of the header file from being copied into the file that #includes it when it has already #included it before.
The #define isn't defining a constant for the struct, but it's simply defining a constant with no value. If that constant was previously defined, the struct will not be redeclared.
It's called "include guard". It protects you from redefinitions occuring when a header is included more than once. There's also non-standard #pragma once that does the same thing, but might not be supported everywhere.
It does not define a constant whose value is the struct. It defines a constant with an empty value.
It's there so that the content of the header is not included twice. Basically it says something like:
if (!bot_h_included)
{
bot_h_included = true;
// code from the header
}
this is called a header guard it stops the compiler compiling or including the code more than once it is similar to pragma once
Just a side note, I don't recommend using #pragma once I see it a lot in a MVC compatible compilers but just a couple of weeks ago I was working with HP UX and the HP-CC does not support #pragma once, I strongly recommend using #ifndef/#define combinations.
Is the #include <file> meant to be used for headers only or is it simply a mechanical "inject this code here" that can be used anywhere in the code?
What if I use it in the middle of a cpp function to just "inject" code from a single source? will this work or will compilers scream about this?
It is a mechanical inject the code here device. You can include a text file containing Goethe's Faust if you wish to. You can put it anywhere, even in the middle of a function (of course, #include needs a fresh line!).
However, it's strong convention to only use #include for header files. There may be reasons where I wouldn't object on it, for example pulling in machine-generated code or merging all translation units in a single file.
Not only does it work anywhere, but it can lead to some interesting techniques. Here's an example that generates an enumeration and a corresponding string table that are guaranteed to be in sync.
Animals.h:
ANIMAL(Anteater)
ANIMAL(Baboon)
...
ANIMAL(Zebra)
AnimalLibrary.h:
#define ANIMAL(name) name,
enum Animals {
#include "Animals.h"
AnimalCount
};
#undef ANIMAL
extern char * AnimalTable[AnimalCount];
AnimalLibrary.cpp:
#include "AnimalLibrary.h"
#define ANIMAL(name) #name,
char * AnimalTable[AnimalCount] = {
#include "Animals.h"
};
main.cpp:
#include "AnimalLibrary.h"
int main()
{
cout << AnimalTable[Baboon];
return 0;
}
Be sure not to put the usual include guards in any file that will be included multiple times!
Gotta agree with William Pursell though that this technique will have people scratching their heads.
Compilers will not complain, but everyone who has to maintain the code will.
It will work - more or less its semantic meaning is: place code in that file here
EDIT: For abusing usages of #include I can just recommend the following:
#include "/dev/console"
This allows for everything: a one-liner that can do everything, an error, its just a matter of compilation...
Should work, it's processed by your preprocessor, your compiler won't even see it.
#include and other preprocessor directives like #define or #import, can appear anywhere in the source, but will only apply to the code after that inclusion. It is meant to include the referenced code into the source file that calls it.
This MSDN page explains it quite well. http://msdn.microsoft.com/en-us/library/36k2cdd4(v=VS.71).aspx
include is handled by the preprocessor and is a mechanism to inject code. There are no restrictions on the file being included or where this #include is placed in your code (thought it should be in its own line). As long as the file specified can be found by the preprocessor it will import its contents into the current file.
Conventionally you do this for header files. I've seen this being done with cpp files during template instantiation (with proper #ifdef so you don't include it multiple times causing multiple symbol definition error).
If you have a long constant, you can do this for other file types as well. (Though there are better ways of handling long string constants)
I want to include a header file only if a certain function body is called?
Is this possible or recommended in C++?
No.
You've got it a bit wrong; #include is not processed at run-time, at all. It's not possible to #include a file based on a program's execution characteristics; once the program executes its source is fixed (since it's already compiled).
Possible, yes; recommended no, not usually.
#include is process and an early stage of parsing so works in many places with no regard for the language context at the point of the include.
Note that the include will happen regardless of whether the function is called so it probably isn't going to solve the problem that you are trying to solve. The file included will be placed directly inside the function body so the include file would have to be designed to be included at such a point in the source file.
You're obviously biased by higher-level languages, such as Python, in which is possible to do things like:
if ( a ):
from whatever import whatever_I_need
else:
from whatever_else import whatever_I_need
However, in C++ this is evaluated at compile time (well, actually, #include is a preprocessor directive and it is even evaluated before compile time). Putting that inside a block of an if-else construction will only lead to compilation errors. Just take into account that #include is just a way to dump the contents of a file (normally a header (interface) file) into another one that needs its declarations. Very low level. It will be included anyway.
You can #include inside a function body, but this does not mean that the header file is only included when the function body is called.
The content of the header file will be included by the preprocessor at compile time, and thus the code will always be present in the function.
Obviously, the code is only executed when the function is called.
While you can put a #include inside a function body, it is not what you want to do. There is no way to include a header file only if a certain function is called because the include happens before compile time, but the function call happens at runtime.
Okay, the question was a little off the track, but the actual matter is important.
If for a portion of your methods you actually need to depend on a library that most users won't care about, it's perfectly reasonable to be willing to spare them this unneeded dependency.
You can do this by manipulating preprocessor tokens.
/// myClass.h
/// In order to use BigDep, you need to:
/// - define `MYPROJECT_BIGDEP_USE` before included this header
/// - have `<bigdep-install-path>/include` in your include path
/// - link with `libbigdep.so`
class MyClass
{
public:
void foo() const;
#ifdef MYPROJECT_BIGDEP_USE
void bigDep() const;
#endif // MYPROJECT_BIGDEP_USE
};
/// myClass.cpp
#include "blah.h"
#include "bar.h"
#ifdef MYPROJECT_BIGDEP_USE
#include <bigdep.h>
#endif // MYPROJECT_BIGDEP_USE
void MyClass::foo() const { /**/ }
#ifdef MYPROJECT_BIGDEP_USE
void MyClass::bigdep() { /**/ }
#endif // MYPROJECT_BIGDEP_USE
This way, you have to compile mode, depending on whether the symbol MYPROJECT_BIGDEP_USE is defined or not.
On gcc, you can define symbol on the command line using -D like in -DMYPROJECT_BIGDEP_USE. On Visual Studio it's with /D like in /DMYPROJECT_BIGDEP_USE.
Another option for you user is to wrap your header:
// myProjectMyClass.h
#define MYPROJECT_BIGDEP_USE
#include <myClass.h>
And only ever include "myProjectMyClass.h" and never your header directly.
The use of these preprocessor directives is quite common. For example, when installing the cx_Oracle python module, the installer checked for the version of oracle I used from my environment variables and disabled a number of methods that were not available for it directly at compilation time.
In one program, that I need to use in my app (using Qt) there's:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
using namespace PL;
"#"include "res/przypisania_txt.h"
MainWindow w;
w.show();
...
and when I paste the include before main, it won't compile, so i gues You can use INCLUDE inside a function ;)