Macro in class definition - c++

class is defined using Macro. Not sure what is the significance of MACRO DEBUG_API here. [I understand #define is used to
turn on or off some specific set of code.] But below code I cannot grasp. any explanation would be appreciated
#define DEBUG_API
class DEBUG_API Cdebug
{
public:
/*
constructor, methods here.
*/
};

When defining this macro, you can choose attributes that will be applied to the class. These can be standard or compiler-specific attributes.
Your particular example is most probably an instance of the usual pattern for DLL headers under MSVC. Depending on a compile-time switch, DEBUG_API will be set to either :
__declspec(dllexport), which will make MSVC generate a .lib file containing the class' thunk; this is used when compiling the library as a DLL;
__declspec(dllimport), which will make MSVC link against the thunk generated above; this is used when linking with the DLL;
Nothing, which won't alter the behaviour of the class. This is used to link statically against the library.

Related

Reason for "{return 0;}" or "{;}" in library's .h file

I am currently working on a project with some old poorly documented code, and am trying to navigate my way through the various .h files that they have provided complete documentation on the use of all of the functions contained (the definitions are held in .lib and .dll files). One of the .h files has functions the are not only declared, but defined with either simple return statements or empty statements as such
class DLL ExampleLibraryClass {
public:
int exampleGetValue() {return 0;}
void exampleSetValue(Type val) {;}
void exampleActionFxn() {;}
};
These would be functions that I expect to return current variable states or perform certain actions, which is why this puzzles me.
Additionally:
I have used Dependency Walker and found that each function does have a matching definition in a dll.
The Keyword DLL has been defined with
#ifndef _PWSDLL_
# define _PWSDLL_
# define WINCALL _stdcall
# ifdef _USRDLL
# define DLL __declspec(dllexport)
# else
# define DLL __declspec(dllimport)
# endif
#endif
_USRDLL is not defined and therefore DLL is defined as __declspec(dllimport)
My question revolves less about the apparent effect of the empty definitions (which do nothing I suppose, and have already been discussed on SO) and more about why the .h file has been written this way and how to utilize the file. Is this a common or known practice? Will the linker still look for definitions to the function in my linked libraries? Are there other pieces of code that I should look for for more clues? Or perhaps in the broadest sense, how should I respond to this?
Many thanks, and please let me know if you need more information to address this, I am unsure what exactly is important in this matter.
EDIT: Added forgotten return types in example code.
EDIT: Added note about DLL definition.
One scenario where you put this code to some use would be to override the functions. These functions hold some default code and could be overridden later.

A strange C++ class declaration

Have read this thread in stackoverflow: Strange class declaration
, but still confused with below code in foo.h:
class Foo CHECKLEAKDCL {
I am sure that Foo should be the class name, since there are constructor and deconstructor which can imply this.
I cannot see any macro definition related with CHECKLEAKDCL in this .h file.
also I am confused with the answer for Strange class declaration , which saying that:
Q_CORE_EXPORT isn't an identifier. It's a platform-dependent macro,
and it's used to signal a class that's intended to be used across
library boundaries.
Can anyone give some more explanation of this?
UPDATE:
found this line in a .h file, which is included in foo.h:
#define CHECKLEAKDCL : private CheckLeak
so the class declarition should be :
class Foo : private CheckLeak {
So Foo is extending CheckLeak, right?
If you compile for windows (using Visual Studio), highly possible it will be evaluated to one of the Microsoft specific linkage identifiers, dllexport or dllimport :
https://msdn.microsoft.com/en-us/library/81h27t8c.aspx
It is used when you create a class which will be exported from a DLL or used from a DLL in an application, and dependig of this it's either evaluated to dllexport (DLL exporting the class) or dllimport (Application importing the class).
If you compile with GCC possibly it will evaluate to one of the gcc _-attribute__s. Such as __attribute__ ((visibility ("default"))) (https://gcc.gnu.org/wiki/Visibility)
These extensions to the core C++ are provided by compilers to make certain tasks more easily achievable (https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Extensions.html)
EDIT
After you updated the answer ... well, obviously you have a private inheritance from a class. But please note, this is a terrible macro you have there because
#define CHECKLEAKDCL : private CheckLeak
adds an : in your class declaration so you cannot use that symbol anymore to inherit from base classes.
I'd recommend that you get rid of that macro altogether, if you cannot, do not use it, it will confuse your code.
We cannot tell exactly what it is, as we have even less information than you do.
Normally, I have seen such macros resolve to export macro, for the library.
That is, the value of it should be defined as dllexport, dllimport or extern (depending on platform). When that is the case though, the macro appears before the class name.
Considering the macro appears after the class name, it can only resolve to a base class, or list of base classes, or an empty macro.
If you have the documentation, search for a base class that tracks or reports it's address to a memory tracker on construction and destruction.
Then, the code base should be compiled using a macrodefinition similar to this:
#define CHECKLEAKDCL() : private MemoryTrackingBaseClass
(where MemoryTrackingBaseClass is the class I mentioned above - according to your edit, CheckLeak).
If you want to simply compile, try using:
#define CHECKLEAKDCL()
Edit (addressing your update)
So Foo is extending CheckLeak, right?
Only when you want to check your application for leaks, using whatever CheckLeak implements.
In a production environment (after you use the definition inheriting from CheckLeak), you should probably define CHECKLEAKDCL as an empty macro (for speed).
As you've discovered, CHECKLEAKDCL is a macro that expands to the three tokens : private CheckLeak. Presumably CheckLeak is a class that adds some leak checking diagnostic behaviour to classes which inherit from it.
In general, this sort of obfuscation is not very helpful. Depending on the properties of CheckLeak, this macro might have unintended side effects, such as turning what appears to be a standard layout class into a non-standard layout class.
It would also be hard to add CHECKLEAKDCL to a class that wanted to inherit from another class for any other reason. (Are you supposed to class Foo CHECKLEAKDCL, public OtherBase ?)
Personally, if given the chance to improve this project I'd favour replacing this macro with its actual expansion in this case.

How do I set up a multi-project solution in C++?

I'm new to C++ and I'm having a hard time getting my dll references to work. I've been trying to get it to work for a couple of days, but the few explainations I've found often refer to doing x or y, but don't tell me how to do x or y. Since I'm not a C++ veteran, I need someone to walk me through it. What I want to do is the following:
MySolution
MyExe (Win32 .exe)
Main.h
Main.cpp
(constructs ImplementationB calls the methods as defined by InterfaceA, then deletes the instances)
(calls/fills HelperC.Foobar)
MyInterfaces (dll)
InterfaceA.h
~InterfaceA();
virtual void DoSomething();
MyUtils (dll)
HelperC.h
static float Foobar;
HelperD.cpp
float HelperC::Foobar = 1.0f;
MyImplementations (dll)
ImplementationB : InterfaceA
(uses the value from HelperC.Foobar)
The MyExe and MyImplementations projects contain most of the executing code. But, I need an interface, so I need an interface project (MyInterfaces). I need some helper classes that need to be accessible from both MyExe and MyImplementations, hence MyUtils. I would like this helper class to be statically available, though it is not mandatory.
I had a compiling version before I started adding MyUtils with the HelperC class. I had to mark the interface destructor with __declspec(dllexport), along with the DoSomething method. I also had to mark the constructor of ImplementationB in order to instantiate it from MyExe, which makes sense. However, when I tried to mark the entire class (both the implementation and the interface) with __declspec(dllexport), the example wouldn't compile (which does not make sense).
From what I've read, having static fields in a dll and using them from external code doesn't really work all too well. So, as an alternative, I made Foobar non-static and passed a HelperC instance to the method as described by InterfaceA. Since I had already gotten simple classes to work, I figured that should work as well. However, now the compiler is throwing errors on the constructor of ImplementationB (LNK2019).
In short: I'm getting link errors all over the place in sections that have nothing to do with my changes, and there's little documentation describing the specific steps I need to perform in order to get a simple dll reference to work.
Can someone point out what I need to add and where I need to add it in order to make it compile? Also, some do's and don't's about C++ dll references would help a lot (e.g. don't use statics across projects).
After much digging, I found out that the culprit was a magical project setting. It is called Ignore Import Library and is located at Project Properties->Linker->General, and is set to Yes by default, while it should be set to No in most cases. The setting tells the executable project to use the dll's lib file during compilation. This still sounds strange to me (sounds like duplicate build output), but as far as I understand it, the lib file describes how to link to the dll. If your dll produces a lib during build, you probably want to set the setting to No.
I also learned that to be able to use the HelperC class as a statically accessible helper, I needed to use dllimport in combination with the macro trick, as described by #drescherjm. The dllimport declaration is only ever needed to be able to use data members across libraries (static class fields or globally defined variables). It may be applied to functions as well, though it is not required, in which case it provides a slight performance boost during library linking.
For completeness, my project structure after getting it to work:
MySolution
MyExe (Win32 .exe, Debugger Type=Mixed)
Main.h
Main.cpp
(constructs ImplementationB calls the methods as defined by InterfaceA, then deletes the instances)
(calls/fills HelperC::Foobar)
MyInterfaces (dll, Ignore Import Library=Yes, because there is no .lib after building)
InterfaceA.h
class __declspec(dllexport) InterfaceA
~InterfaceA() {};
virtual void DoSomething() = 0;
MyUtils (dll, Ignore Import Library=No)
HelperC.h
class __declspec(dllimport/dllexport) HelperC // (see macro trick)
static float Foobar;
HelperD.cpp
float HelperC::Foobar = 1.0f;
MyImplementations (dll, Ignore Import Library=No)
ImplementationB.h
class __declspec(dllexport) ImplementationB : public InterfaceA
ImplementationB();
~ImplementationB();
void DoSomething();
ImplementationB.cpp
ImplementationB::ImplementationB() {};
ImplementationB::~ImplementationB() {};
ImplementationB::DoSomething() { /* Omitted */ };
(uses HelperC::Foobar in implementation)
On a side note: if you added a default C++ class library project in Visual Studio, you may need to flip the Project Properties->Debugging->Debugger Type setting to Mixed before you will be able to set/use breakpoints in the dll code. See this.
I hope this helps others who are wrestling with dll's in C++ (and Visual Studio).

How to work (portably) with C++ class hierarchies & dynamic linked libraries

Ok, so I know portability is not the strong point of C++, but I have to get my code running on both Mac&Windows. I've come up with a solution, but it's not perfect, and I'm interested to see if there is someone out there who can suggest a better one.
I need to us a class hierarchy in several DLLs/bundles - e.g., I have an abstract base class BaseClass; and I scan a given directory for DLLs, and for each DLL, I look for the factory method BaseClass* CreateObject(); - which returns a "BaseClass". I have a "shared header file" that I include both in the "main executable" & in the DLLs, that declares the BaseClass like this
#ifdef _MAC
#define DECLSPEC
#else
#ifdef COMPILING_DLL
#define DECLSPEC __declspec(dllexport)
#else
#define DECLSPEC __declspec(dllimport)
#endif
#endif
class DECLSPEC BaseClass{
[.. base "interface" declaration .. ]
}
And then, in my DLL, I would typically include the BaseClass declaration, and declare my own "concrete" class:
class MyDllClass:public BaseClass{
[.. actual DLL class definition/implementation here goes here ...]
}
So far, so good. Now for some reason, I need to differentiate in my main executable between two different kinds of BaseObjects - say I have a DescriptionClass and an ActionClass, both of which are BaseClass, but have a slightly different interface. My fist implementation was to simply do modify the "shared header" and add:
class DECLSPEC DescriptionClass{
[.. base "Description interface" declaration .. ]
}
class DECLSPEC ActionClass{
[.. base "Action interface" declaration .. ]
}
Then my DLL would become:
class MyDllClass:public ActionClass /* or DescriptionClass, depending on case*/ {
[.. actual DLL class definition/implementation here goes here ...]
}
And in my main executable, I would use it like this:
BaseClass* obj = CreateObjectFromDLL("path_to_dll");
ActionClass* action_obj = dynamic_cast<ActionClass*>(obj);
if(action_obj){
// Do the stuff that is relevant for Action objects
}
DescriptionClass* description_obj = dynamic_cast<ActionClass*>(obj);
if(description_obj){
// Do the stuff that is relevant for Description objects
}
And herein lies the problem: although it works on Windows with Visual Studio (probably due to the MS declspec extension), it fails on Mac (not sure now if it fails on Debug, but I'm sure it fails on release) when compiled with GCC. The reason is simple, even if not immediately obvious: the executable & the dynamic library are compiled separately. Although they both include the declaration of BaseClass, ActionClass, DescriptionClass - these classes are not the same, they are just "identical copies" that are present in the binary and the DLL. So actually, what I'm creating in the DLL is a dll'BaseClass* , which happens to have the same memory layout with main'Baseclass*, so the pointers are compatible, so when I pass the pointer from DLL to EXE, it all works "as expected". OTOH, when I go to a more complex class hierarchy, the vtables/RTTI of dll'ActionClass and main'ActionClass are no longer identical (although in source code they are identical), so when I try do convert (through dynamic_cast) a main'BaseClass* to a main'ActionClass* i get a null result -> because my pointer actually points to a dll'BaseClass object / dll'ActionClass object, and alghough in the DLL I can convert with no proble a "BaseClass*" into a "ActionClass*" - in the main executable, I can't convert the dll's "BaseClass*" into a "ActionClass*", due to the subtle runtime differences between the DLL's and the "main executable's" version of Action Class.
I've "fixed" this by declaring a virtual method in the BaseClass (something like "bool isActionClass()" ), so now I can differentiate... but I'm not very happy with this solution.
Is there something for GCC - e.g. some declaration similar to "__declspec" - a way to guarantee that the same class declared in "main executable" and in "dll" will be 100% compatible?
I actually found the answer to my question due to the fact that I needed to formulate it completely, and I did a better google search :)
It seems to be
__attribute__((dllimport)) // import
__attribute__((dllexport)) // export
Will try that, I thought I'd leave the question here too, in case someone else stumbles on this problem (and as a warning to people that same header file included in a "main binary" & DLL will normaly lead to different actual implementation, depending on the compiler options - unless you put the proper dllimport/export attributes on the class).
That would only work if RTTI is enabled. You, probably, get that automatically enabled in MSVC++, but gcc requires specific link switches. Look in GCC FAQ for details.

How do I prevent my 'unused' global variables being compiled out of my static library?

I'm using static initialisation to ease the process of registering some classes with a factory in C++. Unfortunately, I think the compiler is optimising out the 'unused' objects which are meant to do the useful work in their constructors. Is there any way to tell the compiler not to optimise out a global variable?
class SomeClass {
public:
SomeClass() {
/* do something useful */
}
};
SomeClass instance;
My breakpoint in SomeClass's constructor doesn't get hit. In my actual code, SomeClass is in a header file and instance is in a source file, more or less alone.
EDIT: As guessed by KJAWolf, this code is actually compiled into a static lib, not the executable. Its purpose is to register some types also provided by the static lib with a static list of types and their creators, for a factory to then read from on construction. Since these types are provided with the lib, adding this code to the executable is undesirable.
Also I discovered that by moving the code to another source file that contains other existing code, it works fine. It seems that having a file purely consisting of these global objects is what's causing the problem. It's as if that translation unit was entirely ignored.
The compiler is not allowed to optimiza away global objects.
Even if they are never used.
Somthing else is happening in your code.
Now if you built a static library with your global object and that global object is not referenced from the executable it will not be pulled into the executable by the linker.
The compiler should never optimize away such globals - if it does that, it is simply broken.
You can force that one object (your list of types) pulls some other objects with it by partially linking them before building the complete static lib.
With GNU linker:
ld -Ur -o TypeBundle.o type1.o type2.o type3.o static_list.o
ld -static -o MyStaticLib.a type_bundle.o other_object.o another_object.o ...
Thus, whenever the static list is referenced by code using the library, the complete "TypeBundle.o" object will get linked into the resulting binary, including type1.o, type2.o, and type3.o.
While at it, do check out the meaning of "-Ur" in the manual.
To build off of Arthur Ulfeldt, volatile tells the compiler that this variable can change outside of the knowledge of the compiler. I've used it for put a statement to allow the debugger to set a breakpoint. It's also useful for hardware registers that can change based on the environment or that need a special sequence. i.e. Serial Port receive register and certain watchdog registers.
you could use
#pragma optimize off
int globalVar
#pragma optimize on
but I dunno if that only works in Visual Studio ( http://msdn.microsoft.com/en-us/library/chh3fb0k(VS.80).aspx ).
You could also tell the compiler to not optimize at all, especially if you're debugging...
Are you using gcc with gdb? There was a problem in the past where gdb could not accurately set breakpoints in constructors.
Also, are you using an optimization level which allows the compiler to inline methods in the class definition.
You need to use -whole-archive when linking. See the answer here:
ld linker question: the --whole-archive option
I have same setup & problem on VS2008.
I found that if you declare you class with dllexport it will not optimize.
class __declspec( dllexport ) Cxxx
{
.
}
However this generates a lot of warnings in my case because I must declare all classes used in this class also as dllexport.
All optimizations are off (in debug mode), still this is optimized. Also volatile/pragma optimize off. On global variable created of this class (in same cpp file) etc does not work.
Just found that dllexport does require at least to include header files of these classes in some other cpp file from exe to work! So only option is to add a file with calls to some static members for each class, and add this file to all projects used these classes.
It would not be a compiler, but the library linker (or the tool that pools object files into the .lib), who can decide that the whole file is not used, so discard it.
A workaround would be to add an empty function to that file and call it from a file that contains stuff that is called directly.
How about using the keyword volatile? It will prevent the compiler from too much optimization.