To avoid conflicts with winsock2.h, I want to wrap my include of windows.h with WIN32_LEAN_AND_MEAN (I undef it after windows.h so as not to interfere with applications that include my headers). Doing this causes timeval to be undefined when winsock2.h isn't included. Including time.h doesn't define timeval either.
How can I get timeval defined (a) without having to include winsock2.h, (b) not requiring applications that include my headers to include winsock2.h before my headers, (c) allowing application to include winsock2.h if they need them, and (d) not having to define timeval myself, because it may already be defined by a header the parent application is including?
Remember that WIN32_LEAN_AND_MEAN is a compiler performance optimisation. Using it makes your apps compile somewhat faster at the expense of omitting some less-used parts of the Windows API.
You could use one of the more granular disables (NOIMM, etc), but these have even less impact on compile time than the LEAN_AND_MEAN one does.
Unless your project is very large and has long, onerous compile times I would simply stop using WIN32_LEAN_AND_MEAN.
Martyn
I don't define either of the LEAN_AND_MEANs, instead I explicitly do the following for each of the 'NOs' prior to including windows.h
// Exclude Input Method Manager (International stuff...one day)
#if !defined NOIMM
#define NOIME
#define NOIMM
#endif
// Exclude Metafile API
#if !defined NOMETAFILE
#define NOMETAFILE
#endif
This allows me to use the same StdAfx.h. With VS2010 I can include Winsock2 after windows.h without conflicts.
Stdafx is a little longer, but clearly documents what is included and excluded.
This is how I handle problems with winsock2.h (assuming Visual C++):
I configured the build system to always pass in /D_WINSOCKAPI_ to the compiler on the command line so that no winsock header files are ever implicitly included.
When I want to include winsock2.h, I do it via a proxy header file that does some preprocessor magic for me.
This is how my header file works:
#pragma push_macro("_WINSOCKAPI_")
#undef _WINSOCKAPI_
#include <winsock2.h>
#pragma pop_macro("_WINSOCKAPI_")
If you do this then you don't need to #define WIN32_LEAN_AND_MEAN and you can use winsock2.h only when needed.
I don't think what you want is possible. The timeval struct is defined in winsock.h and winsock2.h, thus you have to include one of those to get the definition. If you don't define WIN32_LEAN_AND_MEAN, windows.h will include winsock.h; this makes it impossible to include winsock2.h. If you define WIN32_LEAN_AND_MEAN, neither of the winsock header files are automatically included thus you don't get the definition for timeval. I think your best option is to require applications to include one of the winsock headers explicitly.
Related
I'm building my own terminal app project in C++ and I'm asking myself if standard library has ifdef or ifndef preprocessors instructions. I want to know that because I need to create different header files which need some standard library headers such as "string" and some others, i don't want to include the same library 3 or more times because it makes the program heavier.
For example i wrote on my header files something like this to prevent the .h file to be included more than once:
#ifndef myheader_h
#define myheader_h
// my file code here
#endif
I tried compiling but the compiler say me nothing about errors or warnings.
I also tried to read the standard-library source code (https://en.cppreference.com/w/cpp/header) and I haven't found any preprocessor rule like ifdef or ifndef.
Should i include standard library headers like this?
#ifndef string_h
#define string_h
#include <string>
#endif
I hope my question isn't already asked because I haven't found it while searching it.
Updates
To some who said "you're not in the position where you need to worry about" and who said "it costs very little if it has proper include guards", I meant: program's heaviness is important, I want to make it slighter so I don't want to entirely include the same file multiple times. Have std lib files proper include guards? (my header files have them, didn't know std lib files)
There is no requirement for the standard header files to #define any specific pre-processor symbols to make sure they can be #included multiple times.
Having said that, any sane implementation would make sure that they can be #included multiple times without adversely affecting application code.
Turns out, that is a requirement by the standard for most headers (Thanks, #Rakete1111).
From the C++ standard
A translation unit may include library headers in any order ([lex]). Each may be included more than once, with no effect different from being included exactly once, except that the effect of including either <cassert> or <assert.h> depends each time on the lexically current definition of NDEBUG.
Not only that, they are very likely to be using the #pragma once directive. Hence, even if you use #include multiple times for the same header, they are going to be read only once.
In summary, don't worry about standard header files. If your header files are implemented correctly, your application would be just fine.
Those preprocessor directives you're talking about are called "header guards", and the standard library headers definitely have them (or some other mechanism that does the same thing) like all other proper header files. Including them multiple times shouldn't cause any problems, and you only need to worry about these when you're writing your own header files.
The "source code" that you're reading is just the documentation which says how the header files should work, but it doesn't provide the actual code. To see the code, you can look in the header files provided by your compiler. For example, the <iostream> header in Visual Studio has both #pragma once and header guards:
#pragma once
#ifndef _IOSTREAM_
#define _IOSTREAM_
//...
#endif /* _IOSTREAM_ */
The headers provided by the GCC compiler also has header guards:
#ifndef _GLIBCXX_IOSTREAM
#define _GLIBCXX_IOSTREAM 1
//...
#endif /* _GLIBCXX_IOSTREAM */
I'm asking myself [sic] if standard library has ifdef or ifndef preprocessors instructions
The standard doesn't specify whether there are ifdef-style header guards, although it does require that multiple inclusion is protected in some manner. I took a look at a random header of stdlibc++ standard library implementation. It does have header guards.
i don't want to include the same library 3 or more times because it makes the program heavier
Including a header file multiple times does not make a program "heavier".
Should i include standard library headers like this?
#ifndef string_h
#define string_h
#include <string>
#endif
That is not necessary, or particularly useful.
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.)
Why can't I include windows.h in afx(MFC) projects?
Typically, MFC application code includes afx.h or afxwin.h (the latter includes former). First two lines of windows.h are
#ifndef _WINDOWS_
#define _WINDOWS_
which means that _WINDOWS_ becomes defined if this header is included.
Afx.h includes afxver_.h and this header includes afxv_w32.h which contains following code:
#ifdef _WINDOWS_
#error WINDOWS.H already included. MFC apps must not #include <windows.h>
#endif
...
#include <windows.h>
So, if you include windows.h before MFC headers, you'll get this error generated in compile time and, as you can see, if you include afxwin.h you don't need to include windows.h yourself - it will already be included by afxv_w32.h.
Because in MFC you are not supposed to use it directly. AFAIR you should include afx.h instead, which in turn indirectly includes windows.h the proper way.
You can include windows.h; but you need to first include afx.h (or similar). If you got the error: "MFC apps must not #include <Windows.h>"; it is from including something like afx.h after including windows.h.
You might need to turn on 'show includes' if not sure how it got included.
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>
When I include winsock2.h, I get about 60 redefinition errors. I hunted around a bit a found some advice to include winsock2.h b4 including windows.h. I did that and that cleared up the errors. My problem and question concerns exactly how I should go about doing this. I did not explicitly include windows.h, it was done for me in stdafx.h or stdafx.cpp.
I added the include winsock2.h immediately b4 the include Windows.h in stdafx.h. Is this the right way to go about this or is there a better way?
Judging by a comment in program_name.rc I gather the windows.h include in stdafx.h may have been placed there as a result of some option or configuration parameter but I was unable to find this reference. Is there some way to specify what files are included in stdafx.h?
BTW, WIN32_LEAN_AND_MEAN was defined b4 calling windows.h in stdafx.h.
I am using Visual c++ 6.0 and 'Windows Server 2003 PSDK' The program is straight c++, no mfc, no net, just plain vanilla.
You can put pretty much whatever you want into stdafx.h. It's certainly fine to add your #include for winsock2.h before the windows.h. I'd move the WIN32_LEAN_AND_MEAN header so that it's defined before you include any other headers:
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <windows.h>
stdafx.h is a horrendous name for the precompiled header. I have no idea why Visual Studio still uses this for all the autogenerated projects. It gives the precompiled header an undeserved air of mystery. In my projects I usually set up the precompiled header to use 'precompiled.h' and 'precompiled.cpp'.
Noel Llopis has a great article on precompiled headers - 'The Care and Feeding of Precompiled Headers' if you want a bit more background info on what's going on here.
That should work okay. If you look in winsock2.h, you can see that it includes windows.h if it hasn't already been included.
You need to make sure that WinSock2.h is included BEFORE windows.h, make sure that wherever you're including WinSock2.h, it is included before stdafx.h and/or windows.h