Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Compatibility Issue #1: stdafx.h

If you’re like me, you’d prefer not to deal with compatibility issues but get right to programming. However, there are a couple of things you need to keep in mind to make sure you succeed with Microsoft Visual Studio.

In order to support something called “precompiled headers,” Microsoft Visual Studio inserts the following line at the beginning of your programs. There’s nothing wrong with this, unless you paste sample code over it and then wonder why nothing works.

#include "stdafx.h"

The problem is that other compilers will not work with this line of code, but programs built with Microsoft Visual Studio require it, unless you make the changes described in this section.

You can adopt one of several strategies to make sure your programs compile inside Microsoft Visual Studio.

  • The easiest thing to do is to make sure this line of code is always the first line in any program created with Visual Studio. So, if you copy generic C++ code listings into a Visual Studio project, make sure you do not erase the directive #includestdafx.h”.
  • If you want to compile generic C++ code (nothing Microsoft-specific), then, when creating a project, do not click the Finish button when the Application Wizard window appears. Instead, click Next. Then, in the Application Settings window, click the “Precompiled Headers” button to de-select it.
  • After a project is created, you can still change settings by doing the following: First, from the Project menu, choose the Properties command (Alt + F7). Then, in the left pane, select Precompiled Headers. (You may first have to expand “Configuration Properties” and then expand “C/C++” by clicking on these words.) Finally, in the right pane, choose “Not Using Precompiled Headers” from the top drop-down list box.

With the last two options, Microsoft-specific lines such as #includestdafx.h” still appear! However, after the Precompiled Headers option box is de-selected, the Microsoft-specific lines can be replaced with generic C++ code.

Also note that Visual Studio uses the following skeleton for the main function:

int _tmain(int arg, _TCHAR* argv[])
{

}

instead of:

int main()
{

}

Both of these work fine with Visual Studio, but if you keep the version that features the word _tmain, remember that it requires #include stdafx.h as well.

The items inside the parentheses, just after _tmain, support access to command-line arguments. But since this book does not address command-line arguments, you won’t need them for the examples in this book. Just leave them as they are.

  • + Share This
  • 🔖 Save To Your Account