Lykias
Lykias

Reputation: 13

Compiling C++ (.cpp) into an .exe file

:) Help greatly appreciated.

I am looking to convert a .cpp file to .exe.

I've tried with (MingW) gcc and g++. I also tried to manually compile it in Visual Studio.

Unfortunately these fail to compile (both on Linux and Windows) because the precompiled headers cannot be located:

stdafx.h: No such file or directory

I've tried to manually download them (the precompiled headers: #include) and change #include <stdafx.h> to #include "stdafx.h" to point at the current folder of the manually downloaded preheaders. This 'works' but it compiles with a massive amount of errors, probably because it's a wrong version of the header (Only place I could find the header was on https://sourceforge.net)

There must be a simpler way?

Upvotes: 0

Views: 4500

Answers (2)

Jossef Harush Kadouri
Jossef Harush Kadouri

Reputation: 34227

You probably used a project template that require stdafx.h.

To solve it you can either remove the #include "stdafx.h" in your cpp files .

Alternatively, toggle off Precompiled header option when creating new project using VS templates. For instance, Win32 Console Application template:

enter image description here

enter image description here

Upvotes: 2

IInspectable
IInspectable

Reputation: 51499

stdafx.h is the default file name used for precompiled header files. This is Visual Studio specific optimization, that compiles rarely changing header files into a binary representation, to speed up compilation.

One quirk of precompiled header files is, that you have to include the header used to create the precompiled header file on the first non-comment/non-whitespace line in every compilation unit. Since this can become impractical (e.g. when using 3rd party libraries in source form), the compiler allows you to include the header file for you. The /FI (Name Forced Include File) compiler switch does just that.

In essence, the solution to your problem is:

  1. Remove the #include <stdafx.h> directive everywhere.
  2. [Optional] Enable creation of precompiled header files in the Visual Studio project.
  3. Use the /FI compiler switch for Visual Studio, in case you opted to create precompiled header files in step 2.

Upvotes: 1

Related Questions