Precompiled header problems - c++

//........Project for ABC.dll
//ABC.h
#pragma once
class ABC{
public:
ABC(){}
private:
std::vector<int> m_vector;
};
//ABC.cpp
#include "Stdafx.h"
#include "ABC.h"
//Stdafx.h
#include <vector>
Till today, I've skipped #include <standard-lib.h> in my headers by delegating it to Stdafx.h header.
It's never been a problem when I worked in a single project file.
Now I'm trying to add a new DLL project to gather shared codes in one project.
It compiled well and generated ABC.dll too.
Here's a problem. When another project that uses ABC.dll show compile error saying that std::vector does not exist.
//...........Another Project using ABC.dll
int main(){
ABC abc;
}
Error C2039 'vector': is not a member of 'std'
To get it working, I had to include all the libraries in the consumer's Stdafx.h too.
Maybe I've been misusing the precompiled header.
I want to know whether the way I've been doing with the PCH was wrong or right.
If it's wrong, I would appreciate it if you suggest right ways of using PCH.
Thanks.

Your problems have nothing to do with precompiled headers. A good practice is to include all the stuff directly used by current file. This will prevent changes in includes of one header file from potentially requiring changes in includes in files that are using this header. vector needs to be included in ABC.h because it is directly used there. Otherwise you'll end up with endless struggling to figure out which headers needs to be included when including this particular library header.

Related

How to include libraries in Visual Studio automatically?

ALWAYS when I start a new class (EX: main.cpp) I need to
#include <iostream>
#include <string>
#include <math.h>
There is a way to make it automatically ? I mean every time when I create a new class they will already be included ?
A cpp file is not a class, it's a source file. A cpp file may include a class, or multiple classes, or no classes. Similar, a header filer is not a librarie, it's just a header file.
Add your includes to a header (.h file), and then your cpp file only has to include that single header to include all those common includes. Visual Studio even has something called a precompiled header, which is exactly meant as such a header with common includes, except that it's precompiled (which means, using that will compile faster than using a regular header). Afaik, you'll still have to include that single header yourself, tho, so you won't get around writing at least one #include ...
My solution is more a workaround than a "real" solution but : You need these lines at least once in your program.
So I'd create a headers_container.hpp file containing stuff my whole program needs, like these #include.
For example :
headers_container.hpp :
#include <iostream>
#include <string>
#include <math.h>
// Some stuff my whole program needs...
in your *.cpp files :
#include "headers_container.cpp"
// Your compiler knows iostream, std::strings and math now
Make sure the path to headers_container.hpp is correct (if the .hpp is not in the same folder as your .cpp
Using this method, you can add one #include in headers_container.hpp and it will update all the .cpp files.
Moreover you can write a small script to generate files (I did the script you can find here : https://gitlab.com/-/snippets/2033889 )
Enjoy your way in programming ! :)

First Time Using PCH, getting Linker Tool Error

I'm a pretty novice programmer, just learning a little bit of c, but I always did it on Linux with gcc and Vim but decided to try using visual studio and I'm getting LNK2005 and LNK1169 errors, I've tried looking up the errors and how to fix them and properly use PCH because I think it would be useful to learn even if my programs are too small to make use of it.
From my understanding I need to #include "stdafx.h" at the top of my source file (called 'helloworld.c') I haven't touched 'stdafx.c' from the default that came when I create the project, I created a header file called 'bitwise.h' and it has one function in it called 'int bw()' I then have 'stdafx.h' and all I added was #include "bitwise.h" In my headerbitwise.h ive tried to include #include "stdafx.h" #include "stdafx.c" #include <stdio.h> and even not including anything. all of these break my program. The only way I can get it to compile is if i comment out//bw(); then my program compiles just fine.
here are the files that I think may be the culprit:
helloworld.c
#include "stdafx.h"
int main()
{
printf("\tHello World!\n");
getchar();
bw(); //If this line is commented out everything works just Honky-Dory
getchar();
return 0;
}
bitwise.h
#include "stdafx.h" //I've tried lots of diffrent lines here, nothing works
int bw()
{
int a = 1;
int x;
for (x = 0; x < 7; x++)
{
printf("\nNumber is Shifted By %i Bits: %i", x, a << x);
}
getchar();
return 0;
}
stdafx.c
// stdafx.cpp : source file that includes just the standard includes
// $safeprojectname$.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
stdafx.h
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include "bitwise.h"
#include <stdio.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
This is not much about PCH. You have mixed up header (.h) and implementation (.c) files. What you need to do is split implementation and declaration. You should do following:
rename your bitwise.h to bitwise.c since this is your implementation file, not a header!
create a new file bitwise.h and put only declaration there, it should look like this:
#pragma once
int bw();
Your project should be able to compile after that.
Please also note PCH file should contain includes that are infrequently changed, which is probably not your case since you are including also bitwise.h. You might want to remove this include from stdafx.h and include it into your helloworld.c.
And just a side note, during learning C do not think of including .c file via #include! If it fixes some of your compilation errors, your project design is probably very wrong.
Nitpick: You should not need to #include stdafx.h in bitwise.h, though it should still have a #pragma once.
Your code for bw() should still be in a separate bitwise.c file, not in the header. I think you may be confusing precompiled headers with function inlining? Right now, your code for bw is being compiled into what is supposed to be the dummy stdafx object, and again in the main object, and causing a conflict when linking.
Also, did you remember to mark your stdafx.h as the precompiled header (/Yu), and the stdafx.cpp as... whatever /Yc is supposed to mean? Make sure both options are set for all project configurations for both files in Properties -> C/C++ -> Precompiled Headers.

Comprehension issue: Precompiled headers & include usage

I got a comprehension issue about precompiled headers, and the usage of the #include directive.
So I got my "stdafx.h" here and include there for example vector, iostream and string. The associated "stdafx.cpp" only includes the "stdafx.h", that's clear.
So if I design my own header file that uses for example "code" that's in vector or iostream, I have to include the header file because the compiler doesn't know the declarations at that time. So why are some posts here (include stdafx.h in header or source file?) saying, it's not good to include the "stdafx.h" in other header files even if this file includes the needed declarations of e.g. vectors? So basically it wouldn't matter to include directly a vector or the precompiled header file, both do the same thing.
I know of course, that I don't have to include a header file in another header file if the associated source file includes the needed header file, because the declarations are known at that time. Well, that only works if the header file is included somewhere.
So my question is: Should I avoid including the precompiled header file in any source file and why? And I am a bit confused, because I'm reading contradictory expressions on the web that I shouldn't include anything in header files anyway, or is it O.K. to include in header files?
So what's right now?
This will be a bit of a blanket statement with intent. The typical setup for PCH in a Visual Studio project follows this general design, and is worth reviewing. That said:
Design your header files as if there is no PCH master-header.
Never build include-order dependencies in your headers that you expect the including source files will fulfill prior to your headers.
The PCH master-header notwithstanding (I'll get to that in a moment), always include your custom headers before standard headers in your source files. This makes your custom header is more likely to be properly defined and not reliant on the including source file's previous inclusion of some standard header file.
Always set up appropriate include guards or pragmas to avoid multiple inclusion. They're critical for this to work correctly.
The PCH master-header is not to be included in your header files. When designing your headers, do so with the intent that everything needed (and only that which is needed) by the header to compile is included. If an including source file needs additional includes for its implementation, it can pull them in as needed after your header.
The following is an example of how I would setup a project that uses multiple standard headers in both the .h and .cpp files.
myobject.h
#ifndef MYAPP_MYOBJECT_H
#define MYAPP_MYOBJECT_H
// we're using std::map and std::string here, so..
#include <map>
#include <string>
class MyObject
{
// some code
private:
std::map<std::string, unsigned int> mymap;
};
#endif
Note the above header should compile in whatever .cpp it is included, with or without PCH being used. On to the source file...
myobject.cpp
// apart from myobject.h, we also need some other standard stuff...
#include "myobject.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
// code, etc...
Note myobject.h does not expect you to include something it relies on. It isn't using <iostream> or <algorithm>, etc. in the header; we're using it here.
That is a typical setup with no PCH. Now we add the PCH master
Adding the PCH Master Header
So how do we set up the PCH master-header to turbo-charge this thing? For the sake of this answer, I'm only dealing with pulling in standard headers and 3rd-party library headers that will not undergo change with the project development. You're not going to be editing <map> or <iostream> (and if you are, get your head examined). Anyway...
See this answer for how a PCH is typically configured in Visual Studio. It shows how one file (usually stdafx.cpp) is responsible for generating the PCH, the rest of your source files then use said-PCH by including stdafx.h.
Decide what goes in the PCH. As a general rule, that is how your PCH should be configured. Put non-volatile stuff in there, and leave the rest for the regular source includes. We're using a number of system headers, and those are going to be our choices for our PCH master.
Ensure each source file participating in the PCH turbo-mode is including the PCH master-header first, as described in the linked answer from (1).
So, first, the PCH master header:
stdafx.h
#ifndef MYAPP_STDAFX_H
#define MYAPP_STDAFX_H
// MS has other stuff here. keep what is needed
#include <algorithm>
#include <numeric>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#endif
Finally, the source files configured to use this then do this. The minimal change needed is:
UPDATED: myobject.cpp
#include "stdafx.h" // <=== only addition
#include "myobject.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
// code, etc...
Note I said minimal. In reality, none of those standard headers need appear in the .cpp anymore, as the PCH master is pulling them in. In other words, you can do this:
UPDATED: myobject.cpp
#include "stdafx.h"
#include "myobject.h"
// code, etc...
Whether you choose to or not is up to you. I prefer to keep them. Yes, it can lengthen the preprocessor phase for the source file as it pulls in the headers, runs into the include-guards, and throws everything away until the final #endif. If your platform supports #pragma once (and VS does) that becomes a near no-op.
But make no mistake: The most important part of all of this is the header myobject.h was not changed at all, and does not include, or know about, the PCH master header. It shouldn't have to, and should not be built so it has to.
Precompiled headers are a method to shorten the build time. The idea is that the compiler could "precompile" declarations and definitions in the header and not have to parse them again.
With the speed of todays computers, the precompilation is only significant for huge projects. These are projects with a minimum of over 50k lines of code. The definition of "signification" is usually tens of minutes to build.
There are many issues surrounding Microsoft's stdafx.h. In my experience, the effort and time spent with discovering and resolving the issues, makes this feature more of a hassle for smaller project sizes. I have my build set up so most of the time, I am compiling only a few files; the files that don't change are not compiled. Thus, I don't see any huge impact or benefit to the precompiled header.
When using the precompiled header feature, every .cpp file must begin by including the stdafx.h header. If it does not, a compiler error results. So there is no point in putting the include in some header file. That header file cannot be included unless the stdafx.h has already been included first.

Single header which includes other headers

Recently, I encountered such approach of managing headers. Could not find much info on its problems on internet, so decided to ask here.
Imagine you have a program where you have main.c, and also other sources and headers like: person.c, person.h, settings.c, settings.h, maindialog.c, maindialog.h, othersource.c, othersource.h
sometimes settings.c might need person.c and main maindialog.c.
Sometimes some other source might need to include other source files.
Typically one would do inside settings.c:
//settings.c
#include "person.h"
#include "maindialog.h"
But, I encountered approach where one has global.h and inside it:
//global.h
//all headers we need
#include "person.h"
#include "maindialog.h"
#include "settings.h"
#include "otherdialog.h"
Now, from each other source file you only have to include "global.h"
and you are done, you get functionality from respective source files.
Does this approach with one global.h header has some real problems?
This is to please both pedantic purists and lazy minimalists. If all sub-headers are done the correct way there is no functional harm including them via global.h, only possible compile time increase.
Subheader would be somewhat like
#ifndef unique_token
#define unique_token
#pragma once
// the useful payload
#endif
If there are common headers that all the source files need, (like config.h) you can do so. (but use it like precompiled headers...)
But by including unnecessary headers, you actually increasing the compilation time. so if you have a really big project and for every source file you including all the headers, compilation time can be very long...
I suggest not include headers unless you must.
Even if you use type, but only for pointer or reference (especially in headers), prefer to use fwd declaration instead of include.

Should re-include stuff thats already in the project scope precompiled header?

I have a precompiled header stdafx.h which is used in all source files in my project. Thus all headers in the stdafx.h are available in all code files in the project.
What I'm unsure about is whether or not to re-include stuff thats already in the precompiled header. What do you guys think?
e.g.
stdafx.h
#pragma once
#include <memory>
my_class.h
#pragma once
#include <memory> // Re-include or not that's the question. Best practice?
struct my_class
{
};
typedef std::shared_ptr<my_class> my_class_ptr;
main.cpp
#include "stdafx.h"
#include "my_class.h"
int main()
{
}
I would include it so that the header could be reused in a project which has different stdafx.h Another way of stating this is each header should contain all the declarations (preferably forward ones) it needs on its own
There will not be any performance hit as the contents of the header will not be processed due to internal header guard (or for VS the #pragma:once in the header file.
In a header you should include everything, that is necessary for that header to be used separately. If you use std::shared_ptr in a header and that template comes from memory header, include memory header.
When you design a header your goal should be to make it complete, so that when someone includes it, he/she doesn't get errors caused by unresolved references. Don't worry that some headers might be included repeatedly. There are other mechanisms to protect against that.
BTW, use those mechanisms (like #pragmaor #ifndef/#define) in your header too.
The best practice would be to use forward declarations as much as possible. Having unnecessary includes might increase compilation time. Always include headers in a file if the implementation uses it even though it was included in a previously included file. This way, if some day you need to remove the header inclusion from the previous file, you will not cause errors in this file and the file won't need any modification.