MFC winsock1 and 2 - c++

I'm deep in trouble with my project.
I have to link two radar with my program, but the first has its own library that uses winsock, while in the second I want to use winsock2.
How can i do that?
At the moment i get many redefinition errors from the includes within winsock.h and winsock2.h.
Take into account that the first radar library is already an DLL, i've got only a header and lib file (no source).
Thank you in advance for any answer.

You could possibly work around the compilation problem by structuring your code (and precompiled headers) so that no file includes both winsock.h and winsock2.h, this may mean either not using precompiled headers at all or using them in a more complex way than is normal in MFC projects...
You could wrap each DLL in a COM object and access them via COM from your main program. This has the advantage of completely separating the use of the two DLLs from your main compilation.
You could wrap each of the DLLs in a new DLL (one each) which provides an interface to your program that does not need the winsock headers in the interface headers.
Of course this may simply be an issue with your Windows.h include order, try putting this at the top of your precompiled header...
#ifndef _WINDOWS_
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#endif
#include <winsock2.h>

Related

C++ preprocessor executing both #ifdef and #ifndef

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.)

Precompiled header error in Visual Studio 2015

I beg your pardon if this question has been already answered, but I have been trying to implement precompiled headers in my game engine with no success so far.
My precompiled header is called UtilBase.h:
#pragma once
#if !defined(NF3D_UTIL_BASE_H)
#define NF3D_UTIL_BASE_H
// This is a precompiled header.
#pragma message("Compiling precompiled header.")
// Include engine specific files.
#include <Utilities\Platform\Types.h>
// Include external header files (STL, Win32 API, Direct3D 11, etc)
// There are some typedefs here:
typedef __int32 int32; // And so on.
#endif
Although this is against the standards, I included UtilBase.h in other headers because I need access to some of its contents. It is also included in all .cpp files, first line, from the current project (the solution has two projects).
I need it in some headers because it stores some typedefs that are used in function declarations. For example, I have some file called Window.h:
#pragma once // And include guards that are omitted here
int32 NF3DCreateWindow();
The associated source file is called UtilBase.cpp and has only one line of code:
#include <Utilities\UtilBase.h>
The project has been set up correctly in my opinion:
for all platforms and configurations.
UtilBase.cpp has this setting:
However, when I compile I get this error:
1>Source Files\Utilities\UtilBase.cpp(2): error C2857: '#include' statement specified with the /YcD:\New Frontiers\NewFrontiers3D\Header Files\Utilities\UtilBase.h command-line option was not found in the source file
which points to the only line in UtilBase.cpp (#include <Utilities\UtilBase.h>).
Why does this happen and what can I do to make it work? I will gladly send any further information about this scenario. Thank you very much in advance.
Finally made it! For anybody in my situation here is what I did: in project settings, Precompiled Header File tag, I added $(ProjDir)\Header Files\Utilities\UtilBase.h and it was evaluated to the full path of the file. The correct way is to simply add the file: Utilities\UtilBase.h and that's it.
Thank you for your support.
try #ifndef instead of #if !defined

Exclude a system header file in VS2010

I'm wondering how to exclude a specified system header file in VS2010, which makes an ambiguous problem.
In my project, I use an opensource project. In which a cpp file calls
std::something::max()
where the max is a method in something.
However, max is also defined in a system header file "minwindef.h", which in my case lies at \Windows Kits\8.0\shared\minwidef.h
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
I think this is not necessary for my project.
So how do I manually prohibit this file to be included (perhaps recursively)?
You might want to #define NOMINMAX before #includeing any Windows headers.
This is such a common problem that they added this macro to remove the min and max definitions that conflict with the stl versions.
I'll try and dig up some MSDN reference for this.
Most likely, your opensource project is not designed to be "mixed" with "windows" headers.
Just don't do #include <windows.h> into the same files that include your opensource project. The limit the includes of <windows.h> to only be included in files that ABSOLUTELY need to have it, and idealy have one or more files with "windows only" functionality that are then provided to the rest of the code via it's own headers, isolating any windows functionality - that will also help if you ever decide to port your system to something other than windows.
(There are whole bunch of other macros that will sooner or late come back and bite you if you keep including Windows in your overall project)

Ideal way to include headers from a DLL?

I've been testing things with multiple project setups where a console application accesses functions from several DLLs.
I thought about how to include the DLLs' headers in the console application. My current implementation is as follows but it's being a headache to manage and even sometimes runs into errors:
Each DLL project has a folder called "Include"
The Console application project references the Include folder of each DLL project (as suggested by msdn guide to working with DLLs)
Each DLL project contains a single header that includes all the headers in that one project
The console application then #includes these "master headers"
Every project uses the pre-compiled header "stdafx" and each file #includes it.
It worked out fine until I started overloading operators.
I believe the grief is caused by the pre-compiled header somehow, here's and example of my current usage of stdafx:
#define DLL // Found in every DLL, not in the console project
#ifdef DLL
#define DLLEI __declspec(dllexport)
#else
#define DLLEI __declspec(dllimport)
#endif
#include <iostream>
#include <vector>
#include "Include\Engine.h"
using namespace std;
With this I sometimes get some irrelevant random compiler errors that I can hackfix by excluding the header from the "master header" and including the troublemaker separately in the console app.
Suggestions what could be done better?
__declspec(dllexport) and __declspec(dllimport) definitions should be placed in every public Dll include file, or at least in the main Dll public include file, which includes all other files. These definitions should not be in stdafx.h.
#define DLL // Found in every DLL, not in the console project
This is incorrect, every Dll must have unique preprocessor definition. In your case, of one Dll depends on another, it always compiles another Dll functions as __declspec(dllexport)
Ensure that every header has #pragma once in the beginning.
Consider using common Include directory for all projects.
As already mentioned in the comments, using namespace can be used only in source files.
This article answered quite a few of my questions.
http://www.codeproject.com/Articles/6351/Regular-DLL-Tutor-For-Beginners

precompiled header files usage for library builders

According to this answer boost and STL headers belong into the precompiled header file (stdafx.h in the MSVC world). So I changed the headers of my dynamic link library project and moved all STL/Boost headers into the stdafx.h of my project.
Before
#include <boost/smart_ptr.hpp>
namespace XXX
{
class CLASS_DECL_BK CExampleClass // CLASS_DECL_BK is just a standard dll import/export macro
{
private:
boost::scoped_ptr<Replica> m_replica;
}
}
After
namespace XXX
{
class CLASS_DECL_BK CExampleClass
{
private:
boost::scoped_ptr<Replica> m_replica;
}
}
Now I have the advantage of decreased compile times, but all the users of my library are getting build errors (e.g. unknown boost::scoped_ptr...) because of the missing includes (which are now moved to my stdafx.h).
What could be a solution for this dilemma?
I want reduced compile times and compile errors after including my headers files are not acceptable for any users of the dll.
Could this help?
leave all includes directives as they are but duplicate them in my 'stdafx.h'? Since the stdafx.h is always included first inside any cpp file of my project I should be fine, and the users won't get any errors. Or do I loose the speed advantage if multiple includes of the same header occur in one translation unit (got header guards)?
Thanks for any hints!
You should get nearly the same speed increase when you leave the header-includes in place in the library headers and just additionally put them into stdafx.h.
Alternatively, you could add an additional define (a bulk external include guard)
// stdafx.h
#define MY_LIB_STD_HEADERS_ALREADY_INCLUDED
// library_file.h
#ifndef MY_LIB_STD_HEADERS_ALREADY_INCLUDED
#include <boost/smart_ptr.hpp>
...
#endif
But I would only do that if you are sure it helps. Just take a stopwatch and run a few re-compilations. (No need to link.) Then you'll see if there's any difference.
Aside
I'm not sure if adding all boost headers that are needed somewhere in the project is such a good idea. I'd say shared_ptrand friends, boost/foreach, maybe Boost.Format, ... are a good idea, but I'd already think twice for the Boost.RegExp headers. Note: I did not do any speed measurements, but I dimly remember a problem with the size of the pch file and some compiler hiccup. I really should do some tests.
Also check if the Boost Library in question provides forwarding headers and whether you should include them instead. Bloating the precompiled header file can have it's downsides.
you could create a build configuration for this purpose (Debug, Release, CheckDependencies). a simple way to change this would be to use the preprocessor to include/exclude the includes based on the current configuration. using this, you can test and build using debug or release (which contains the larger set of includes), then build all configurations before distribution.
to clarify, the conditional include MON_LIBRARY_VALIDATE_DEPENDENCIES is not to be used in the library headers or sources, only in the precompiled header:
// my pch:
#include <file1.hpp>
#include <file2.hpp>
// ...
#if !defined(MON_LIBRARY_VALIDATE_DEPENDENCIES)
#include <boost/stuff.hpp>
// ...
#endif
then you would append MON_LIBRARY_VALIDATE_DEPENDENCIES to the list of preprocessor definitions in the CheckDependencies configuration.
regarding guards: it should not be a problem if you are using guards under normal circumstances - compilers use optimizations to detect these cases which means they can avoid opening the file in many cases if it's been multiply included and guarded correctly. in fact, attempts to outsmart the compiler in this arena can actually slow down to process. i'd say just leave it as typical unless your library/dependencies are huge and you really have noticeable problems.
Making your compilation units selfcontained (let them include everything they use) is very desirable. This will prevent compilation errors from others that do not use precompiled headers, and as you assume, header guards will keep the cost of these extra includes minimal.
This will also have the desirable side effect that a glance at the headers will tell the users which other headers are in use in the unit, and the options of doing a compilation of the single unit without any fuzz.