I am building a library project and a test project to test this library on. I want the user (A.K.A. the test project) to be able to define some things for the library, but the #define is not recognized in my library and just throws an error.
**I am building the library project as static library, the build order is that the library builds first and then the test project since the project is dependent on the library.
In the test project I want the user to be able to define like this (before the include):
#define PUT_DEFINE_HERE
In the library I just check with:
#ifdef PUT_DEFINE_HERE
//Do some stuff
#endif
As stated before the library does not see the #define defined by the user. I tried some stuff with the build order but no luck so far, any ideas?
If you want the library to "accept" a user #define, the check on the presence of PUT_DEFINE_HERE
#ifdef PUT_DEFINE_HERE
//Do some stuff
#endif
must be done at the header lever, and only there
Secondly, the user project which includes the library header must #define PUT_DEFINE_HERE before including the library header.
Alternatively, if such a setting is incompatible with the library design, then the #define must be added at compile time, e.g.:
gcc -DPUT_DEFINE_HERE ...
In this case, be sure to compile every source with -DPUT_DEFINE_HERE, when relevant.
Related
So I'm currently working on something that uses OpenCL. The OpenCL spec provides the users with a directive which must be included before the inclusion of the header (cl.h)
#define CL_TARGET_OPENCL_VERSION 110
Which basically defines the version they want to use. Suppose I'm making a library and I want my users to define this instead of me defining this inside my files. What I did was.
-----main.cpp---
#define CL_TARGET_OPENCL_VERSION 110
#include "library.h"
-------x---------
----library.h-----
#ifdef CL_TARGET_OPENCL_VERSION
#pragma message("def")
#endif
#ifndef CL_TARGET_OPENCL_VERSION
#pragma message("ndef")
#endif
.... include other headers.
--------x---------
And the compiler prints both def and ndef messages. And the OpenCL library also throws a warning that it's undefined. I thought that the library header would get substituted into main and it'd only print the def message. Is there anything I understood wrong?
I'm particularly confused as to where does the preprocessor start? If it starts from main.cpp and goes from top to down, then it surely has defined the macro. After that it sees the library inclusion, then it should only print the def message but it prints both.
This leds me to believe the preprocessor does scan the header file before including it in main? Dunno the reason why. Also I have assured that the library header isn't included elsewhere.
One interesting thing I noticed was, if i did this
-----helper.h---
#define CL_TARGET_OPENCL_VERSION 110
-------x---------
----library.h-----
#include helper.h
#ifdef CL_TARGET_OPENCL_VERSION
#pragma message("def")
#endif
#ifndef CL_TARGET_OPENCL_VERSION
#pragma message("ndef")
#endif
.... include other headers.
--------x---------
It prints the def message "twice". If anybody can explain all this I'd be grateful.
EDIT:- The files I'm compiling are main.cpp library.h and library.cpp
Library.cpp includes library.h from the start as usual. Maybe this other cpp is causing the problem?
In C/C++ programs, the compiler handles each .c and .cpp file separately.
The compilers build each source file (NOT the header files, only .c and .cpp files) independently from each other (this source files are called compilation unit).
Thus, when your main.cpp is built, the compiler finds the #define CL_TARGET_OPENCL_VERSION 110 you have added on top of the main.cpp file, emiting the defmessage.
But when the compiler builds the library.cpp file, it does not find the version define, so it emits the ndef message.
So, following this explanation, it is completely normal that in your last case, when you add the define to the .h file, the compiler emits the def message twice, once for the main.cpp file and once for the library.cpp file.
Now, the problem is where should you add the define, in order to have the program built consistently, with the same version for all the .cpp files.
Usually, all the IDEs have some configuration page where you can add global defines, for all the project, which are "inserted" into all the compilation units before everything else. So when the IDE calls the compiler, it passes the same defines to all the compilation units. You should add this kind of defines in this page.
In your IDE (I am using Code::Blocks, v 17.12), you can find this page in the menu: Project / Build Options
For each type (Debug or Release), you have to go to the tab Compiler Settings, and there to the sub tab #defines. There you can add global defines, which can be different if you are building in Debug or in Release mode (of course, if you set the same in both modes, they would be the same).
Once you have added your define here, please, remove it from the main.cpp, library.h and any other place where you may have added it, in order to avoid duplicities.
From the comments about portability:
You have several options:
Always use Code::Blocks: this would be the easiest way, since you can pass the Code::Blocks project along with the source files, and everything would be already setup.
Use cmake, which is a script build system, where you can set defines and so in the same way as using an IDE. cmake is much widely used than Code::Blocks, so maybe it is a better option.
Add a new options.h header file, where you set all the defines, and include it to all your .c/.cpp. This setup has the additional benefit that for different systems, changing only the options.h file the build can be completely different. This is a manually setup of what the IDE is doing. It has the advantage that does not rely on external tools, but the disadvantage that you have to remember to add it in all the new .cpp files added to the project.
My recommendation is go with cmake, just as the others have said.
Prefer using #ifndef XXXX_h #define XXXX_h #endif over #pragma once
If your #include search path is sufficiently complicated, the compiler may be unable to tell the difference between two headers with the same basename (e.g. a/foo.h and b/foo.h), so a #pragma once in one of them will suppress both. It may also be unable to tell that two different relative includes (e.g. #include "foo.h" and #include "../a/foo.h" refer to the same file, so #pragma once will fail to suppress a redundant include when it should have.
This also affects the compiler's ability to avoid rereading files with #ifndef guards, but that is just an optimization. With #ifndef guards, the compiler can safely read any file it isn't sure it has seen already; if it's wrong, it just has to do some extra work. As long as no two headers define the same guard macro, the code will compile as expected. And if two headers do define the same guard macro, the programmer can go in and change one of them.
#pragma once has no such safety net -- if the compiler is wrong about the identity of a header file, either way, the program will fail to compile. If you hit this bug, your only options are to stop using #pragma once, or to rename one of the headers. The names of headers are part of your API contract, so renaming is probably not an option.
(The short version of why this is problematic to use #pragma is that neither the Unix nor the Windows filesystem API offer any mechanism that guarantees to tell you whether two absolute pathnames refer to the same file.)
My objective is to create a dll and lib file so i'm following this guide
1) I created a new win32 Console Application project in VS, chose DLL as 'Application Type' and Emptied Project
2) I'm trying to create a database in C++. So I have 5 headers with ONLY function declarations.
3) Database.h is my top header, it looks like this:
#ifdef DBDLL_EXPORTS
#define DBDLL_API __declspec(dllexport)
#else
#define DBDLL_API __declspec(dllimport)
#endif
#ifndef __Database_H
#define __Database_H
#include "Table.h"
class DBDLL_API Database { ... };
#endif
4) Now with only headers, I tried compiling the project. It compiled but I don't see any DLLs or Libs anywhere in the project folder. How do I create them?
This is because headers are not compiled -- only CPP files are compiled (which pull in the headers -- a source file and all the headers it pulls in is called a "translation unit", which is the thing actually being compiled (independent of other TUs)).
So, in effect, the build system thinks you're building an empty project, and in this case generates nothing at all. Note that even if the headers are pulled in and compiled, unless an exported symbol is actually referenced somewhere, it may be optimized out. In such cases, you will get an (empty) DLL, but no .lib file (which can cause errors down the line if you have dependent projects looking for this .lib before there's anything in the DLL).
You'll need to create some CPP files that implement the functions declared in the headers. If you have everything in the headers and don't need any CPP files at all, then there's no point in having a DLL! (Since you could include the headers in any other project without needing any other dependency.)
Finally, your include guard (#ifndef ...) should encompass the entire header, including the DLL export macros, otherwise you'll eventually get macro redefinition warnings.
I would suggest using #pragma once instead of include guards since it's simpler and recognized by pretty much every compiler. I would also put the DLL macro goop into its own header (e.g. "dllmacros.h") and include that where it's needed (this will reduce duplication).
In a *.cpp file, trying to use a third party lib:
#define DLL_IMPORT
#include <thirdParty.h>
// Third party header has code like:
// #ifdef DLL_IMPORT
// #define DLL_DECL __declspec(dllimport)
// fatal error C1001: An internal error has occurred in the compiler.
Alternative:
#define NO_DLL
#include <thirdParty.h>
// Third party header has code like:
// #elif defined(NO_DLL)
// #define DLL_DECL
// Compiles fine, but linker errors as can't find DLL functions
I can reproduce results by remove macros and #define all together and manually editing the third party files to have __declspec(dllimport) or not - so the preprocessor stuff above is just to show what's going on, it's not copy-paste.
Has anyone come across anything similar, or can hint at the cause? (which is created using CMake). Above is actual example of 2 line *.cpp that crashes so it's narrowed down to something in the #include.
The following also work fine:
Compile the examples provided by the third party (they provide a *.sln) that use dllimport/export so it doesn't appear to be the fault of the library
Compile the third party lib as part of the production project (so dllexport works fine)
I've trawled the project settings pages of the two projects to try and spot differences, but have come up blank. Of course, it's possible I'm missing something as those settings pages are not the easiest to navigate. I'll get access to VS2008 in a day or so, so can compare with that. The third party library is MySql++.
A compiler crash is definitely a bug in the compiler, so you're best off submitting an error report to the Microsoft Visual C++ team.
As for the error
#define DLL_DECL __declspec(dllimport)
is the wrong way to go about things. There should be some project setting you need to set, a pre-processing directive you can define instead if DLL_DECL, or simply including a different file.
Turns out it was because precompiled headers was turned on for the project trying to use the DLL.
let's say I am distributing a library as binary. It is shipped in two versions, debug and release. Debug and release are incompatible with each other, so if e.g. the user builds a release executable, he/she must link with release library.
If there is a mismatch between library and executable versions, currently there will be subtle errors that are really hard to figure out. I would instead like to show a really clear error message that informs there is a mismatch, preferably at link time.
What would be a good way to achieve this?
I'm going to assume that you are using a static library and by binary you mean a .lib that will be linked at compile time (as opposed to a dll or the like that might be mismatched at run-time).
Seems to me the easiest way is to have this sort of a construct in your .h file
#ifdef _RELEASE //or whatever your compiler uses
#define InitialiseLibrary InitialiseLibraryRelease
#else
#define InitialiseLibrary InitialiseLibraryDebug
#endif
Similarly in the cpp file of the library:
#ifdef _RELEASE //or whatever your compiler uses
void InitialiseLibraryRelease()
{
CommonInitialise();
}
#else
void InitialiseLibraryDebug()
{
CommonInitialise();
}
#endif
Now in the main exe which is using the library:
InitialiseLibrary();
If the release-ness of the library and exe don;t match then the linker will report not matching one or other InitialiseLibrary... function.
A different option is to ensure that the release and debug libraries compile to differently named files and then get the link to work using #pragma in the .h file (as opposed to explicitly including the library in a project).
Using the #ifdef as above you can select at compile time which library to link by choosing which #pragma is used. This second technique doesn't exactly address your question (as it doesn't STOP the link happening if the programmer tries to force it) but it is a normal way of dealing with difficulties of this sort (and has advantages in complex build environments)
Could also checksum the binaries/libraries in your install script. Not a C answer, though.
Use #error directive, that will abort the compilation:
#ifndef RELEASE_VERSION
#error Release version required
#endif
How can I remove this link warning? You can see code segment that causes this warning.
static AFX_EXTENSION_MODULE GuiCtrlsDLL = { NULL, NULL };
//bla bla
// Exported DLL initialization is run in context of running application
extern "C" void WINAPI InitGuiCtrlsDLL()
{
// create a new CDynLinkLibrary for this app
new CDynLinkLibrary(GuiCtrlsDLL);
// nothing more to do
}
warning C4273: 'InitGuiCtrlsDLL' : inconsistent dll linkage
I have also export and import definitions, like:
#ifdef _GUICTRLS
#define GUI_CTRLS_EXPORT __declspec(dllexport)
#else
#define GUI_CTRLS_EXPORT __declspec(dllimport)
#endif
The purpose of the preprocessor statements:
#ifdef _GUICTRLS
#define GUI_CTRLS_EXPORT __declspec(dllexport)
#else
#define GUI_CTRLS_EXPORT __declspec(dllimport)
#endif
is to make sure that the header file declares the class or function as __declspec(dllexport) in the .dll where it is defined, and as __declspec(dllimport) for any other .dll that might want to use it.
For this to work, _GUICTRLS must be defined when compiling the exporting .dll, and not defined for any other .dll. Generally you would expect _GUICTRLS to be defined in the project properties, under C/C++ -> Preprocessor -> Preprocessor Definitions.
The compiler error you are seeing usually happens because either _GUICTRLS is not defined for the project that is doing the export, or it is defined for multiple projects, usually resulting from cutting an pasting from one project to another. You will also see this if _GUICTRLS is defined in a header file that is included in multiple projects.
There are multiple possibilities:
1) static AFX_EXTENSION_MODULE GuiCtrlsDLL = { NULL, NULL };
You use AFX_EXTENSION_MODULE. This means that you are implementing an MFC extension DLL. For such extension dlls you have to define the preprocessor _AFXEXT. Set this in the C++ compiler settings of your Visual C++ project
see:
How To Use _declspec(dllexport) in an MFC Extension DLL: http://support.microsoft.com/kb/128199
AFX_EXTENSION_MODULE Structure: http://msdn.microsoft.com/en-us/library/sxfyk0zk.aspx
TN033: DLL Version of MFC: http://msdn.microsoft.com/en-us/library/hw85e4bb.aspx
2) It is likely that you have a duplicated definiton/declaration.
In addition to reading the warning message, pay attention to where it occurs if you have multiple projects as part of a workspace.
I wasted time looking for a problem in my DLL which was compiling and linking correctly. The workspace was also building the main application and my error was that I had inadvertently included a new (DLL) source file into the build file list of the application itself.
The main program requires the DLL header mynewdll.h to import things but does not require the source file mynewdll.cpp. (The code is brought in at run time with a DLL.) I have a habit of including header and code files into projects as a pair, and this is where I had gone wrong.
I would have detected the error much sooner if I had been alert and noticed that the DLL project linked with no errors and it was the main program that complained!
My DLL source code and project was error free and it was only the way I tried to build my executable that was faulty.
That warning is usually caused by a duplicate definition of a function with different use of dllimport. Are you sure you didn't do this?
[ CMake inconsistent dll linkage ]
I encountered the following issue + solution with the __declspec(dllexport) + __declspec(dllimport) :
# # #CMakeLists.txt
add_defintions(-DMYLIB=1)
# The above was the solution...
# (MYLIB is used in the standard ifdef + define MYLIB_EXPORT syntax)
# Below: seems to get overruled by other directory's headers:
set_source_files_properties( file1.h file2.h COMPILE_FLAGS "-DMYLIB=1")
This was annoying because a number of sources say to use the 'set source file properties' command to get better granularity but the doc is not clear on what happens to file1.h's declares when included from a different directory... better stick with add_definitions( -DMYLIB=1 ) for now!
To catch this problem: in your Foo.cpp file:
#include "export.h"
#if defined(MYLIB)
#if defined(OTHERLIB)
static_assert(0,"error, check your definitions!");
// OTHER depends on MY; can't have both of these flags being set!
#endif
#endif
struct OTHER_EXPORT foo
{
};
See that you are not defining the exported symbols in a different project. Also clean all the intermediate files by hand and recompile.
To elaborate the answer of damian with an example. I read it but didn't understand at first glance.
You have a shared library with a source file compiled in that contains the function. In a new project you use the library and in addition you compile also the source file to use the function (I forgot that it is already in the library). Within the library the functions label is exported, within the additional compiled source file the functions label is marked to be imported. That's the conflict.
In my case, error C4273 was caused by trying linking to .lib file from a DLL dynamic load tester app in Qt5 by msvc2017_64 toolchain. Removing the reference to .lib file by changing LIBS setting in .pro file have the problem solved.