How can I undeclare DECLARE_HANDLE? - c++

I'm porting a piece of code from VC6 to VS2008. The code typedefs HSPRITE as int. But Windows SDK 6.1 already declared HSPRITE through DECLARE_HANDLE. I don't want to rename HSPRITE in my code since it will consume a lot of time to rename it in .cpp files. So, how can I undeclare HSPRITE?

The only correct way is to not include the header that defines HSPRITE, which may not be an option.
Alternatively you should check out one of the following:
Do you really use HSPRITE as an int? Maybe you can remove the definition of HSPRITE from your code and use the one defined in windows' headers.
Use Find and Replace to rename HSPRITE to some other name in your code; it's a matter of a few seconds.

Best is what #ybungalobill says. If you absolutely cannot use his answer, you can also trick windows.h into not declaring it, like this:
#define HSPRITE DeletedWinapi_HSPRITE// prevent windows.h from defining it
#include <windows.h>
#undef HSPRITE
typedef int HSPRITE;

Related

C++ preprocessor: test if class exists [duplicate]

Is there such macro in C++ (cross-compiler or compiler-specific):
#if isclass(NameSpace::MyClass)
Would be useful.
No. Preprocessing directives and macros are evaluated by the preprocessor, which completes its tasks before the code is parsed as C++. The preprocessor has no knowledge of classes or namespaces.
If you do not care about portability, the __if_exists statement in VC++ meets your needs.
There is no such thing at the preprocessing stage, so no macro.
However you can have a look at the is_class type traits available in Boost or in C++0x that enable you to take decisions at compile time.
That's not possible, but you could use your include guard constant to verify that the class has been included.
It sounds to me like it would be better to test if the header file with the class definition you're looking for has been included yet, instead of trying to see if the class exists. It's really easy to check this if you've been implementing the standard of defining a symbol for each header file, as shown:
// myfile.h
#ifndef _MYFILE_H_
#define _MYFILE_H_
// CODE
#endif // _MYFILE_H_
Your best bet though, is to just make sure your header files are being included in the right order in the first place. The easiest way to do this is to have an "overall" header file that in turn includes all the headers you will need in the correct order. Simply include that in each of the source files in your project, and you'll be good to go. This isn't necessarily the best solution, but it is the easiest.

In C/C++, is there a directive similar to #ifndef for typedefs?

If I want to define a value only if it is not defined, I do something like this :
#ifndef THING
#define THING OTHER_THING
#endif
What if THING is a typedef'd identifier, and not defined? I would like to do something like this:
#ifntypedef thing_type
typedef uint32_t thing_type
#endif
The issue arose because I wanted to check to see if an external library has already defined the boolean type, but I'd be open to hearing a more general solution.
There is no such thing in the language, nor is it needed. Within a single project you should not have the same typedef alias referring to different types ever, as that is a violation of the ODR, and if you are going to create the same alias for the same type then just do it. The language allows you to perform the same typedef as many times as you wish and will usually catch that particular ODR (within the same translation unit):
typedef int myint;
typedef int myint; // OK: myint is still an alias to int
//typedef double myint; // Error: myint already defined as alias to int
If what you are intending to do is implementing a piece of functionality for different types by using a typedef to determine which to use, then you should be looking at templates rather than typedefs.
C++ does not provide any mechanism for code to test presence of typedef, the best you can have is something like this:
#ifndef THING_TYPE_DEFINED
#define THING_TYPE_DEFINED
typedef uint32_t thing_type
#endif
EDIT:
As #David, is correct in his comment, this answers the how? part but importantly misses the why? It can be done in the way above, If you want to do it et all, but important it you probably don't need to do it anyways, #David's answer & comment explains the details, and I think that answers the question correctly.
No there is no such facility in C++ at preprocessing stage. At the max can do is
#ifndef thing_type
#define thing_type uint32_t
#endif
Though this is not a good coding practice and I don't suggest it.
Preprocessor directives (like #define) are crude text replacement tools, which know nothing about the programming language, so they can't act on any language-level definitions.
There are two approaches to making sure a type is only defined once:
Structure the code so that each definition has its place, and there's no need for multiple definitions
#define a preprocessor macro alongside the type, and use #ifndef to check for the macro definition before defining the type.
The first option will generally lead to more maintainable code. The second could cause subtle bugs, if you accidentally end up with different definitions of the type within one program.
As other have already said, there are no such thing, but if you try to create an alias to different type, you'll get a compilation error :
typedef int myInt;
typedef int myInt; // ok, same alias
typedef float myInt; // error
However, there is a thing called ctag for finding where a typedef is defined.
The problem is actually real PITA, because some APIs or SDKs redefine commonly used things. I had issue that header files for a map processing software (GIS) were redefining TRUE and FALSE (generally used by windows SDK)keywords to integer literals instead of true and false keywords ( obviously, that can break SOMETHING). And yes, famous joke "#define true false" is relevant.
define would never feel a typedef or constant declared in C\C++ code because preprocessor doesn't analyze code, it only scans for # statements. And it modifies code prior to giving it to syntax analyzer. SO, in general, it's not possible.
https://msdn.microsoft.com/en-us/library/5xkf423c.aspx?f=255&MSPPError=-2147217396
That one isn't portable so far, though there were known request to implement it in GCC. I think, it also counts as "extension" in MSVC. It's a compiler statement, not a preprocessor statement, so it will not "feel" defined macros, it would detect only typedefs outside of function body. "full type" there means that it will react on full definition, ignoring statements like "class SomeClass;". Use it at own risk.
Edit: apparently it also supported on MacOS now and by Intel comiler with -fms-dialect flag (AIX\Linux?)
This might not directly answer the question, but serve as a possible solution to your problem.
Why not try something like this?
#define DEFAULT_TYPE int // just for argument's sake
#ifndef MY_COOL_TYPE
#define MY_COOL_TYPE DEFAULT_TYPE
#endif
typedef MY_COOL_TYPE My_Cool_Datatype_t;
Then if you want to customize the type, you can either define MY_COOL_TYPE somewhere above this (like in a "configure" header that is included at the top of this header) or pass it as a command line argument when compiling (as far as I know you can do this with GCC and LLVM, maybe others, too).
No there is nothing like what you wanted. I have had your same problem with libraries that include their owntypedefs for things like bool. It gets to be a problem when they just don't care about what you use for bool or if any other libs might be doing the same thing!!
So here's what I do. I edit the header file for the libs that do such things and find the typedef bool and add some code like this:
#ifdef USE_LIBNAME_BOOL
typedef unsigned char bool; // This is the lib's bool implementation
#else
#include <stdbool.h>
#endif
Notice that I included if I didn't want to use the libs' own bool typdef. This means that you need C99 support or later.
As mentioned before this is not included in the C++ standard, but you might be able to use autotools to get the same functionality.
You could use the ac_cxx_bool macro to make sure bool is defined (or different routines for different datatypes).
The solution I ended up using was including stdbool.h. I know this doesn't solve the question of how to check if a typedef is already defined, but it does let me ensure that the boolean type is defined.
This is a good question. C and Unix have a history together, and there are a lot of Unix C typedefs not available on a non-POSIX platform such as Windows (shhh Cygwin people). You'll need to decide how to answer this question whenever you're trying to write C that's portable between these systems (shhhhh Cygwin people).
If cross-platform portability is what you need this for, then knowing the platform-specific preprocessor macro for the compilation target is sometimes helpful. E.g. windows has the _WIN32 preprocessor macro defined - it's 1 whenever the compilation target is 32-bit ARM, 64-bit ARM, x86, or x64. But it's presence also informs us that we're on a Windows machine. This means that e.g. ssize_t won't be available (ssize_t, not size_t). So you might want to do something like:
#ifdef _WIN32
typedef long ssize_t;
#endif
By the way, people in this thread have commented about a similar pattern that is formally called a guard. You see it in header files (i.e. interfaces or ".h" files) a lot to prevent multiple inclusion. You'll hear about header guards.
/// #file poop.h
#ifndef POOP_H
#define POOP_H
void* poop(Poop* arg);
#endif
Now I can include the header file in the implementation file poop.c and some other file like main.c, and I know they will always compile successfully and without multiple inclusion, whether they are compiled together or individually, thanks to the header guards.
Salty seadogs write their header guards programmatically or with C++11 function-like macros. If you like books I recommend Jens Gustedt's "Modern C".
It is not transparent but you can try to compile it one time without typedef (just using the alias), and see if it compiles or not.
There is not such things.
It is possible to desactivate this duplicate_typedef compilator error.
"typedef name has already been declared (with same type)"
On a another hand, for some standardized typedef definition there is often a preprocessor macro defined like __bool_true_false_are_defined for bool that can be used.

Can I redefine a C++ macro then define it back?

I am using both the JUCE Library and a number of Boost headers in my code. Juce defines "T" as a macro (groan), and Boost often uses "T" in it's template definitions. The result is that if you somehow include the JUCE headers before the Boost headers the preprocessor expands the JUCE macro in the Boost code, and then the compiler gets hopelessly lost.
Keeping my includes in the right order isn't hard most of the time, but it can get tricky when you have a JUCE class that includes some other classes and somewhere up the chain one file includes Boost, and if any of the files before it needed a JUCE include you're in trouble.
My initial hope at fixing this was to
#undef T
before any includes for Boost. But the problem is, if I don't re-define it, then other code gets confused that "T" is not declared.
I then thought that maybe I could do some circular #define trickery like so:
// some includes up here
#define ___T___ T
#undef T
// include boost headers here
#define T ___T___
#undef ___T___
Ugly, but I thought it may work.
Sadly no. I get errors in places using "T" as a macro that
'___T___' was not declared in this scope.
Is there a way to make these two libraries work reliably together?
As greyfade pointed out, your ___T___ trick doesn't work because the preprocessor is a pretty simple creature. An alternative approach is to use pragma directives:
// juice includes here
#pragma push_macro("T")
#undef T
// include boost headers here
#pragma pop_macro("T")
That should work in MSVC++ and GCC has added support for pop_macro and push_macro for compatibility with it. Technically it is implementation-dependent though, but I don't think there's a standard way of temporarily suppressing the definition.
Can you wrap the offending library in another include and trap the #define T inside?
eg:
JUICE_wrapper.h:
#include "juice.h"
#undef T
main.cpp:
#include "JUICE_wrapper.h"
#include "boost.h"
rest of code....
I then thought that maybe I could do some circular #define trickery like so:
The C Preprocessor doesn't work this way. Preprocessor symbols aren't defined in the same sense that a symbol is given meaning when, e.g., you define a function.
It might help to think of the preprocessor as a text-replace engine. When a symbol is defined, it's treated as a straight-up text-replace until the end of the file or until it's undefined. Its value is not stored anywhere, and so, can't be copied. Therefore, the only way to restore the definition of T after you've #undefed it is to completely reproduce its value in a new #define later in your code.
The best you can do is to simply not use Boost or petition the developers of JUCE to not use T as a macro. (Or, worst case, fix it yourself by changing the name of the macro.)

How to define a function with same name which is present in different file

I want to define a class like this
class HttpRestAccessor
{
public:
IResource& UpdateResource(string& , IResource& );
};
and implementing in cpp file
IResource& HttpRestAccessor::UpdateResource(string& resourceUri, IResource& resource)
this cpp file refers to Winbase.h which has defined UpdateResource as follows
#define UpdateResource UpdateResourceW
And hence while compiling i get following error
error C2039: 'UpdateResourceW' : is not a member of 'RestToolkit::HttpRestAccessor'
this problem would be solved if rename function name to something different.
but I would love to keep my function name as UpdateResource.
Thanks In Advance,
Uday
Just undefine it:
#undef UpdateResource
then redefine later if you actually need it.
EDIT: However, you should reconsider your aversion to renaming the method. As others have said, that's a more elegant solution.
Macro's totally ignore scope.
Basically the pre-precessor will do a find/replace of UpdateResource with UpdateResourceW so you're all out of luck.
renaming the method is your only option
The simplest way is to include winbase.h before all other headers (in stdafx.h) so that you don't care whether the method name is replaced.
Rename your function. If you want to use windows libraries then you have to accept they take precedence, you'd never try to create a class called std::string would you?
Ugh, that is the evil of the preprocessor!
you could use the #undef preprocessor directive to undefine the UpdateResource macro before you declare you function.
One way is to document that if Winbase.h is included, it must be included before this header. Normally that would be a horrible requirement, but with Windows headers, it's pretty much a given that you're in for a world of pain unless you include them first (normally in a precompiled header, as #sharptooth says).
That done, put this in your header:
#ifdef UpdateResource
#pragma push_macro("UpdateResource")
#undef UpdateResource
#endif
Anyone simultaneously needing the original definition of UpdateResource and your class just needs to put
#pragma pop_macro("UpdateResource")
Namespace is the way to go.

Is there a clean way to prevent windows.h from creating a near & far macro?

Deep down in WinDef.h there's this relic from the segmented memory era:
#define far
#define near
This obviously causes problems if you attempt to use near or far as variable names. Any clean workarounds? Other then renaming my variables?
You can safely undefine them, contrary to claims from others. The reason is that they're just macros's. They only affect the preprocessor between their definition and their undefinition. In your case, that will be from early in windows.h to the last line of windows.h. If you need extra windows headers, you'd include them after windows.h and before the #undef. In your code, the preprocessor will simply leave the symbols unchanged, as intended.
The comment about older code is irrelevant. That code will be in a separate library, compiled independently. Only at link time will these be connected, when macros are long gone.
Undefine any macros you don't want after including windows.h:
#include <windows.h>
#undef near
#undef far
maybe:
#undef near
#undef far
could be dangerous though...
You probably don't want to undefined near and far everywhere. But when you need to use the variable names, you can use the following to undefine the macro locally and add it back when you are done.
#pragma push_macro("near")
#undef near
//your code here.
#pragma pop_macro ("near")
Best not to. They are defined for backwards compatibility with older code - if you got rid of them somehow and then later needed to use some of that old code you'd be broken.