Меню

Include stdafx h ошибка как исправить

When I compiled this program (from C++ Programming Language 4th edition):

main.cpp

#include <stdafx.h>
#include <iostream>
#include <cmath>
#include "vector.h"
using namespace std;

double sqrt_sum(vector&);

int _tmain(int argc, _TCHAR* argv[])
{
    vector v(6);
    sqrt_sum(v);
    return 0;
}

double sqrt_sum(vector& v)
{
    double sum = 0;
    for (int i = 0; i != v.size(); ++i)
        sum += sqrt(v[i]);
    return sum;
}

vector.cpp

#include <stdafx.h>
#include "vector.h" 

vector::vector(int s)
:elem{ new double[s] }, sz{ s }
{
}
double& vector::operator[](int i)
{
    return elem[i];
}
int vector::size()
{
    return sz;
}

vector.h

#include <stdafx.h>
class vector{
public:
    vector(int s);
    double& operator[](int i);
    int size();
private:
    double* elem;
    int sz;
};

It gave me these errors:

errors

I run it on Microsoft Visual Studio 2013, on Windows 7. How to fix it?

Sensei James's user avatar

asked Oct 12, 2014 at 21:28

Kulis's user avatar

1

You have to properly understand what is a «stdafx.h», aka precompiled header. Other questions or Wikipedia will answer that. In many cases a precompiled header can be avoided, especially if your project is small and with few dependencies. In your case, as you probably started from a template project, it was used to include Windows.h only for the _TCHAR macro.

Then, precompiled header is usually a per-project file in Visual Studio world, so:

  1. Ensure you have the file «stdafx.h» in your project. If you don’t (e.g. you removed it) just create a new temporary project and copy the default one from there;
  2. Change the #include <stdafx.h> to #include "stdafx.h". It is supposed to be a project local file, not to be resolved in include directories.

Secondly: it’s inadvisable to include the precompiled header in your own headers, to not clutter namespace of other source that can use your code as a library, so completely remove its inclusion in vector.h.

answered Oct 12, 2014 at 21:42

ceztko's user avatar

ceztkoceztko

14.5k5 gold badges54 silver badges73 bronze badges

5

Just include windows.h instead of stdfax or create a clean project without template.

answered Oct 12, 2014 at 22:05

user3718058's user avatar

user3718058user3718058

2831 gold badge3 silver badges11 bronze badges

There are two solutions for it.

Solution number one:
1.Recreate the project. While creating a project ensure that precompiled header is checked(Application settings… *** Do not check empty project)

Solution Number two:
1.Create stdafx.h and stdafx.cpp in your project
2 Right click on project -> properties -> C/C++ -> Precompiled Headers
3.select precompiled header to create(/Yc)
4.Rebuild the solution

Drop me a message if you encounter any issue.

answered Jun 11, 2016 at 6:51

Dila Gurung's user avatar

Dila GurungDila Gurung

1,61821 silver badges25 bronze badges

1

You can fix this problem by adding «$(ProjectDir)» (or wherever the stdafx.h is) to list of directories under Project->Properties->Configuration Properties->C/C++->General->Additional Include Directories.

answered Sep 13, 2018 at 15:46

Sar's user avatar

SarSar

1151 silver badge6 bronze badges

Add #include "afxwin.h" in your source file. It will solve your issue.

Al Lelopath's user avatar

Al Lelopath

6,32313 gold badges81 silver badges135 bronze badges

answered Jun 29, 2015 at 10:29

Dila Gurung's user avatar

Dila GurungDila Gurung

1,61821 silver badges25 bronze badges

Just running through a Visual Studio Code tutorial and came across a similiar issue.

Replace #include "stdafx.h" with #include "pch.h" which is the updated name for the precompiled headers.

Marius's user avatar

Marius

1,4996 silver badges20 bronze badges

answered Dec 26, 2018 at 13:07

Robert Morel's user avatar

Problem

This message appears during the compilation of Microsoft Visual® C++ code generated by IBM Rational® Rose®:
«Cannot open include file: ‘stdafx.h’: No such file or directory»?

Cause

As the error message says, the compiler is finding an include statement for the header file «stdafx.h», but can’t find the file itself.

Rose is generating the following line: #include «stdafx.h» by default.

#include «stdafx.h»

The file stdafx.h is usually used as a precompiled header file. Precompiled headers help to speed up compilation when a group of files in a project do not change.

Resolving The Problem

If a precompiled header is not used, this include shouldn’t get generated in the code. To turn it off, open the Visual C++ Component Properties dialog and in the tab «Includes» delete the text in the «Initial Source Includes».

Another possibility is to create an empty «stdafx.h» file.

For more information about precompiled header files, refer to the Microsoft knowledge base.

[{«Product»:{«code»:»SSSHEM»,»label»:»Rational Rose Enterprise»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Component»:»—«,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»2003.06.00″,»Edition»:»»,»Line of Business»:{«code»:»LOB45″,»label»:»Automation»}}]

Historical Number

152592215

Добавлено 27 марта 2021 в 12:55

В этом разделе мы рассмотрим некоторые из распространенных проблем, с которыми, похоже, начинающие программисты сталкиваются с довольно высокой вероятностью. Это не исчерпывающий список проблем компиляции или запуска программ, а скорее прагматичный список решений самых основных проблем. Если у вас есть предложения по другим вопросам, которые могут быть добавлены в этот список, опубликуйте их в разделе комментариев ниже.

Общие проблемы во время выполнения

Вопрос: При выполнении программы окно консоли мигает, а затем сразу закрывается.


Сначала добавьте или убедитесь, что следующие строки находятся в верхней части вашей программы (пользователи Visual Studio должны убедиться, что эти строки появляются после #include "pch.h" или #include "stdafx.h", если таковые существуют):

#include <iostream>
#include <limits>

Во-вторых, добавьте следующий код в конец функции main() (прямо перед оператором return):

// сбрасываем все флаги ошибок
std::cin.clear();
// игнорируем любые символы во входном буфере, пока не найдем новую строку
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
// получаем от пользователя еще один символ
std::cin.get();

Это заставит вашу программу ждать, пока пользователь нажмет любую клавишу, прежде чем продолжить, что даст вам время изучить вывод вашей программы, прежде чем ваша операционная система закроет окно консоли.

Другие решения, такие как обычно предлагаемое system("pause"), могут работать только в определенных операционных системах, и их следует избегать.

Более старые версии Visual Studio могут не приостанавливаться, когда программа запускается в режиме Начать с отладкой (Start With Debugging) (F5). Попробуйте запустить в режиме Начать без отладки (Start Without Debugging) (Ctrl + F5).

Вопрос: Я запустил свою программу, получил окно, но ничего не выводится.


Выполнение может блокировать ваш антивирус. Попробуйте временно отключить его и посмотрите, не в этом ли проблема.

Вопрос: Моя программа компилируется, но работает некорректно. Что не так?


Отладьте ее! Советы по диагностике и отладке программ приведены далее в главе 3.

Общие проблемы времени компиляции

Вопрос: Когда я компилирую свою программу, я получаю ошибку о неразрешенном внешнем символе _main или _WinMain@16


Это означает, что ваш компилятор не может найти вашу функцию main(). А все программы должны включать в себя эту функцию.

Есть несколько вещей, которые нужно проверить:

  1. Содержит ли ваш код функцию с именем main?
  2. Правильно ли написано имя main?
  3. Когда вы компилируете свою программу, видите ли вы, что файл, содержащий функцию main(), компилируется? Если нет, либо переместите функцию main() в другой файл, либо добавьте этот файл в свой проект (для получения дополнительной информации о том, как это сделать, смотрите урок «2.7 – Программы с несколькими файлами кода»).
  4. Вы точно создали консольный проект? Попробуйте создать новый консольный проект.

Вопрос: Я пытаюсь использовать функциональность C++11/14/17/XX, но она не работает.


Если у вас старый компилятор, он может не поддерживать эти более свежие дополнения к языку. В этом случае обновите свой компилятор.

В случае с современными IDE/компиляторами ваш компилятор может по умолчанию использовать более старый стандарт языка. Мы рассмотрим, как изменить стандарт языка в уроке «0.12 – Настройка компилятора: выбор стандарта языка».

Вопрос: При попытке использовать cin, cout или endl компилятор говорит, что cin, cout или endl являются «необъявленными идентификаторами».


Во-первых, убедитесь, что вы включили следующую строку в верхней части файла:

#include <iostream>

Во-вторых, убедитесь, что каждое использование cin, cout и endl имеет префикс «std::«. Например:

std::cout << "Hello world!" << std::endl;

Если это не решит вашу проблему, возможно, ваш компилятор устарел или установка повреждена. Попробуйте переустановить и/или обновить компилятор до последней версии.

Вопрос: При попытке использовать endl для завершения напечатанной строки компилятор говорит, что end1 является «необъявленным идентификатором».


Убедитесь, что вы не перепутали букву l (нижний регистр L) в endl с цифрой 1. endl – это все буквы. Убедитесь, что ваш редактор использует шрифт, который проясняет разницу между строчной буквой L, заглавной i и цифрой 1. Кроме того, во многих шрифтах, не предназначенных для программирования, можно легко перепутать заглавную букву o и цифру ноль.

Проблемы с Visual Studio

Вопрос: При компиляции с помощью Microsoft Visual C++ вы получаете фатальную ошибку C1010 с сообщением типа «c:vcprojectstest.cpp(263) :fatal error C1010: unexpected end of file while looking for precompiled header directive» (неожиданный конец файла при поиске директивы предварительно скомпилированного заголовка).


Эта ошибка возникает, когда компилятор Microsoft Visual C++ настроен на использование предварительно скомпилированных заголовков, но один (или несколько) ваших файлов кода C++ не включает #include "stdafx.h" или #include "pch.h" в качестве первой строки кода файла.

Предлагаемое нами решение – отключить предварительно скомпилированные заголовки, как это сделано в уроке «0.7 – Компиляция вашей первой программы».

Если вы хотите, чтобы предварительно скомпилированные заголовки были включены, чтобы решить эту проблему, просто найдите файл(ы), вызывающий ошибку (в приведенной выше ошибке виновником является test.cpp), и добавьте следующую строку в самом верху файла):

#include "pch.h"

В более старых версиях Visual Studio используется stdafx.h вместо pch.h, поэтому, если pch.h не решает проблему, попробуйте stdafx.h.

Обратите внимание, что для программ с несколькими файлами каждый файл кода C++ должен начинаться с этой строки.

Кроме того, вы можете отключить предварительно скомпилированные заголовки.

Вопрос: Visual Studio выдает следующую ошибку: «1MSVCRTD.lib(exe_winmain.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function «int __cdecl invoke_main(void)» (?invoke_main@@YAHXZ)» (неразрешенный внешний символ _WinMain@16).


Скорее всего, вы создали не консольное приложение, а графическое приложение Windows. Создайте заново свой проект и убедитесь, что вы создали его как консольный проект Windows (или Win32).

Вопрос: Когда я компилирую свою программу, я получаю предупреждение «Cannot find or open the PDB file» (не могу найти или открыть файл PDB).


Это предупреждение, а не ошибка, поэтому оно не должно повлиять на вашу программу. Однако она раздражает. Чтобы исправить это, перейдите в меню Debug (Отладка) → Options and Settings (Параметры) → Symbols (Символы) и установите флажок Microsoft Symbol Server (Сервер символов Microsoft).

Прочее

Вопрос: У меня есть еще одна проблема, которую я не могу понять. Как я могу быстро получить ответ?


По мере обучения у вас, несомненно, будут возникать вопросы или неожиданные проблемы. Что делать дальше, зависит от вашей проблемы. Но в целом есть несколько вещей, которые вы можете попробовать.

Сначала спросите Google. Найдите хороший способ сформулировать свой вопрос и выполните поиск в Google. Если вы получили сообщение об ошибке, вставьте точное сообщение в Google, используя кавычки. Скорее всего, кто-то уже задавал тот же вопрос, и вы найдете ответ.

Если это не поможет, спросите на сайте вопросов и ответов. Существуют веб-сайты, предназначенные для вопросов и ответов о программировании, например, Stack Overflow. Попробуйте разместить там свой вопрос. Не забудьте подробно описать, в чем заключается ваша проблема, и включить всю необходимую информацию, например, какую ОС и какую IDE вы используете.

Теги

C++ / CppFAQLearnCppДля начинающихОбучениеПрограммирование

Visual C++ allows you to define several ways of setting up precompiled header files. The most common is to enable it for ALL source files at the project configuration level, Under Configuration Properties/C++/Precompiled Headers, setting «Precompiled Header», select «Use». The same location, setting «Precompiled Header File», is usually «stdafx.h». All files will get this setting (thus the configuration at the project) EXCEPT….

One file is responsible for generating the PCH file. That file is typically the stdafx.cpp file in your project, and it typically has nothing in it except #include "stdafx.h". Configuring Precompiled Headers for THAT ONE FILE, switch from «Use» to «Create». This ensures that if the prime-header for PCH gets out of synch stdafx.cpp is ALWAYS compiled first to regenerate the PCH data file. There are other ways of configuring PCH setting in Visual Studio, but this is the most common.

That being said, your problem is definitely irritating. The filename used to prime the PCH system and specified on both the «Use…» and «Create…» setting above MUST MATCH THE TEXT IN YOUR #include EXACTLY.

Therefore, it is highly likely you can address your problem by adding «..» to your project include directories and removing the «..» from your #include statement. you could also change it at the project-configuration level to be «..stdafx.h» as the through-header, but that might be a problem if you have source files in multiple folders hierarchically.

Oh, and if it wasn’t clear to you while perusing the PCH configuration settings, if you do NOT want to use PCH for any specific source file (and there are reasons not to sometimes) you can turn it OFF for specific source files, otherwise be sure to always have #include «your-pch-include-file.h» at the head of every source file (c/cpp,etc).

Hope you catch a break.

Visual C++ allows you to define several ways of setting up precompiled header files. The most common is to enable it for ALL source files at the project configuration level, Under Configuration Properties/C++/Precompiled Headers, setting «Precompiled Header», select «Use». The same location, setting «Precompiled Header File», is usually «stdafx.h». All files will get this setting (thus the configuration at the project) EXCEPT….

One file is responsible for generating the PCH file. That file is typically the stdafx.cpp file in your project, and it typically has nothing in it except #include "stdafx.h". Configuring Precompiled Headers for THAT ONE FILE, switch from «Use» to «Create». This ensures that if the prime-header for PCH gets out of synch stdafx.cpp is ALWAYS compiled first to regenerate the PCH data file. There are other ways of configuring PCH setting in Visual Studio, but this is the most common.

That being said, your problem is definitely irritating. The filename used to prime the PCH system and specified on both the «Use…» and «Create…» setting above MUST MATCH THE TEXT IN YOUR #include EXACTLY.

Therefore, it is highly likely you can address your problem by adding «..» to your project include directories and removing the «..» from your #include statement. you could also change it at the project-configuration level to be «..stdafx.h» as the through-header, but that might be a problem if you have source files in multiple folders hierarchically.

Oh, and if it wasn’t clear to you while perusing the PCH configuration settings, if you do NOT want to use PCH for any specific source file (and there are reasons not to sometimes) you can turn it OFF for specific source files, otherwise be sure to always have #include «your-pch-include-file.h» at the head of every source file (c/cpp,etc).

Hope you catch a break.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Inarc dll вернул код ошибки 11
  • In5p поло седан что значит ошибка