Fatal error c1189 error no target architecture

Well, first of all, why are you including winnt.h, for anything Windows related, unless noted otherwise, you should include windows.h and only that. Winnt.h is included by windef.h, and windef.h is included by windows.h. But winnt.h won't pull in anything else it needs so it needs to be included at the right time. Which is why you should only include the Windows master header file, winnt.h.

Well, first of all, why are you including winnt.h, for anything Windows related, unless noted otherwise, you should include windows.h and only that. Winnt.h is included by windef.h, and windef.h is included by windows.h. But winnt.h won’t pull in anything
else it needs so it needs to be included at the right time. Which is why you should only include the Windows master header file, winnt.h.

For the preprocessor definitions, you shouldn’t need to add anything at all. The project I am currently working on which includes windows.h has the following set for the preprocessor definitions

WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) for debug

WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) for release

which surprisingly is identical to my 32 bit build.

So why is it coming up with no target architecture. Well, _AMD64_ and _IA64_ are not predefined macros according to
this list, so where does it pick up the definition from. Well, near the middle of windows.h, before windef.h is included, there are the following definitions.

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_IX86)
#define _X86_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_AMD64)
#define _AMD64_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_M68K)
#define _68K_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_MPPC)
#define _MPPC_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_M_IX86) && !defined(_AMD64_) && defined(_M_IA64)
#if !defined(_IA64_)
#define _IA64_
#endif /* !_IA64_ */
#endif

Now, you should recognise some of these definitions, especially the _M_xxx definitions. This means that the _AMD64_ definition is defined in Windows.h. So that is one mystery solved. Now, what about the syntax errors, well, as I already said, winnt.h won’t
pull in anything else. It relies on the fact that you are including things in the right order. A good example of this is that things like WINAPI and the basic typedefs are defined in windef.h before winnt.h is included. So this would lead to problems such
as on line 130 of winnt.h where it uses DWORD, but DWORD is defined in windef.h before winnt.h is included, so this means that directly including winnt.h, it will never pick up this definition of DWORD.

Finally, documentation on the MSDN always tells you to include windows.h, for example, look at
JOBOBJECT_BASIC_LIMIT_INFORMATION. In the requirements section near the bottom, you will see Header: Winnt.h (include Windows.h). So there is at least one documented instance of it telling
you to not directly include winnt.h.


Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts
is to aid in the learning process.
Visit my (not very good) blog at
http://ccprogramming.wordpress.com/

  • Marked as answer by
    Jesse Jiang
    Wednesday, January 19, 2011 3:44 AM

Содержание

  1. Error no target architecture winnt h
  2. Answered by:
  3. Question
  4. Answers
  5. Error no target architecture winnt h
  6. Answered by:
  7. Question
  8. Answers
  9. Error no target architecture winnt h
  10. Answered by:
  11. Question
  12. Answers
  13. Error: building python3 on rs4 sdk fails in winnt.h: No target architecture #3047
  14. Comments
  15. Неустранимая ошибка: «Нет целевой архитектуры» в Visual Studio
  16. 11 ответы

Error no target architecture winnt h

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

First of all, sorry for my english.

I try to build a 64bit solution using VisualStudio2010, but I have a trouble.
This is the error message: includeWinNT.h(165): fatal error C1189: #error : «No Target Architecture»

I think I’ve correctly configured the «Configuration Manager. » whit x64 platform, and with the project properties.
The error occures here:

If I try to insert this before the #if defined:

I’ve also insert the WIN64, _WIN64, DBG, DEBUG, _DEBUG, WINNT=1 Preprocessor Definition in C/C++ -> Preprocessor project’s properties, but the error is the same.

In addition if I try to insert also the _AMD64_ Prepocessor Definition, the compiler return me a lot of error, ever on WinNT.h, like that: WinNT.h(381): error C2146: syntax error : missing ‘;’ before identifier ‘WCHAR’

Where am I wrong in this?

Thanks in advice!

Answers

For now I solved the problem by removing the include winnt.h , because not entirely necessary .

Thank you all for the answers .

Well, first of all, why are you including winnt.h, for anything Windows related, unless noted otherwise, you should include windows.h and only that. Winnt.h is included by windef.h, and windef.h is included by windows.h. But winnt.h won’t pull in anything else it needs so it needs to be included at the right time. Which is why you should only include the Windows master header file, winnt.h.

For the preprocessor definitions, you shouldn’t need to add anything at all. The project I am currently working on which includes windows.h has the following set for the preprocessor definitions

WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) for debug

WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) for release

which surprisingly is identical to my 32 bit build.

Источник

Error no target architecture winnt h

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

First of all, sorry for my english.

I try to build a 64bit solution using VisualStudio2010, but I have a trouble.
This is the error message: includeWinNT.h(165): fatal error C1189: #error : «No Target Architecture»

I think I’ve correctly configured the «Configuration Manager. » whit x64 platform, and with the project properties.
The error occures here:

If I try to insert this before the #if defined:

I’ve also insert the WIN64, _WIN64, DBG, DEBUG, _DEBUG, WINNT=1 Preprocessor Definition in C/C++ -> Preprocessor project’s properties, but the error is the same.

In addition if I try to insert also the _AMD64_ Prepocessor Definition, the compiler return me a lot of error, ever on WinNT.h, like that: WinNT.h(381): error C2146: syntax error : missing ‘;’ before identifier ‘WCHAR’

Where am I wrong in this?

Thanks in advice!

Answers

For now I solved the problem by removing the include winnt.h , because not entirely necessary .

Thank you all for the answers .

Well, first of all, why are you including winnt.h, for anything Windows related, unless noted otherwise, you should include windows.h and only that. Winnt.h is included by windef.h, and windef.h is included by windows.h. But winnt.h won’t pull in anything else it needs so it needs to be included at the right time. Which is why you should only include the Windows master header file, winnt.h.

For the preprocessor definitions, you shouldn’t need to add anything at all. The project I am currently working on which includes windows.h has the following set for the preprocessor definitions

WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) for debug

WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) for release

which surprisingly is identical to my 32 bit build.

Источник

Error no target architecture winnt h

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

First of all, sorry for my english.

I try to build a 64bit solution using VisualStudio2010, but I have a trouble.
This is the error message: includeWinNT.h(165): fatal error C1189: #error : «No Target Architecture»

I think I’ve correctly configured the «Configuration Manager. » whit x64 platform, and with the project properties.
The error occures here:

If I try to insert this before the #if defined:

I’ve also insert the WIN64, _WIN64, DBG, DEBUG, _DEBUG, WINNT=1 Preprocessor Definition in C/C++ -> Preprocessor project’s properties, but the error is the same.

In addition if I try to insert also the _AMD64_ Prepocessor Definition, the compiler return me a lot of error, ever on WinNT.h, like that: WinNT.h(381): error C2146: syntax error : missing ‘;’ before identifier ‘WCHAR’

Where am I wrong in this?

Thanks in advice!

Answers

For now I solved the problem by removing the include winnt.h , because not entirely necessary .

Thank you all for the answers .

Well, first of all, why are you including winnt.h, for anything Windows related, unless noted otherwise, you should include windows.h and only that. Winnt.h is included by windef.h, and windef.h is included by windows.h. But winnt.h won’t pull in anything else it needs so it needs to be included at the right time. Which is why you should only include the Windows master header file, winnt.h.

For the preprocessor definitions, you shouldn’t need to add anything at all. The project I am currently working on which includes windows.h has the following set for the preprocessor definitions

WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) for debug

WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) for release

which surprisingly is identical to my 32 bit build.

Источник

Error: building python3 on rs4 sdk fails in winnt.h: No target architecture #3047

  • VS 2017 15.6 latest stable public release
  • Windows Insider SDK 17115 (latest Insider preview release)
    vcpkg install python3

The usual cause of this failure is failing to include Windows.h before other Windows platform SDK headers, I’m trying to see if I can find the specific compilation unit that’s failing.

The text was updated successfully, but these errors were encountered:

Note: including file: d:srcvcpkgbuildtreespython3src-x86-windowscpython-3.6.4modules_io_iomodule.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0umconsoleapi.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0sharedapiset.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0sharedapisetcconv.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0sharedminwindef.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0sharedspecstrings.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0sharedspecstrings_strict.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0sharedspecstrings_undef.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0shareddriverspecs.h
Note: including file: d:programfileswindowskits10include10.0.17115.0sharedsdv_driverspecs.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0sharedwinapifamily.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0sharedwinpackagefamily.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0umwinnt.h
Note: including file: D:ProgramFilesWindowsKits10include10.0.17115.0sharedkernelspecs.h
d:programfileswindowskits10include10.0.17115.0umwinnt.h(154): fatal error C1189: #error: «No Target Architecture»

modules/_io/_iomodule.c just needs one tweak:

#ifdef MS_WINDOWS
#include
#include
#endif

What is the best way to go about this — start with a patch for vcpkg and then try to request the change upstream?

Источник

Неустранимая ошибка: «Нет целевой архитектуры» в Visual Studio

Когда я пытаюсь скомпилировать свой проект c ++ с помощью Visual Studio 2010 в режиме Win32 или x64, я получаю следующую ошибку:

>C:Program Files (x86)Microsoft SDKsWindowsv7.0Aincludewinnt.h(135): fatal error C1189: #error : «No Target Architecture»

Мои определения препроцессора говорят: WIN32; _DEBUG; _CONSOLE;% (PreprocessorDefinitions)

Что вызывает эту ошибку и как ее исправить?

Обновление: я создал новый проект msvs и скопировал в него свой код. У меня больше нет error : «No Target Architecture» , но теперь у меня есть несколько ошибок компиляции, связанных с winnt.h и winbase.h, и никаких ошибок компиляции, связанных с какими-либо из моих файлов. Возможно, эти файлы повреждены? Нужно ли мне переустанавливать MSVS 2010?

Обновление 2: я сузил круг своей проблемы и обнаружил, что это #include это вызывает все мои ошибки компиляции с winnt.h, но я все еще не знаю, как это исправить.

Как установить целевую архитектуру для моего проекта? — philipvr

В этом случае ванильный проект не провалится. Что вы изменили по сравнению с ванильным проектом? Что находится в строке 135 файла winnt.h? Вы хоть раз смотрели эту строку заголовочного файла. Сообщение об ошибке дает вам некоторую помощь. — David Heffernan

вы сможете решить это отсюда; вероятно, нужно вернуться до строки 127, хотя, чтобы получить полную картину. Казалось бы, ясно, что Эдвин был прав. — David Heffernan

Попробуйте новый проект msvs (фиктивный) и скопируйте и перетащите в него свои источники. Попробуйте скомпилировать его, и если это так, сравните его с вашим исходным проектом. Кстати, не копируйте stdafx. * — engf-010

Звучит плохо. Но перед повторной установкой вы можете сначала попробовать его с новым решением, и если это не сработает, вы можете вручную переустановить project = templates (погуглите). — engf-010

11 ответы

Используйте #include вместо #include .

Из windows.h страница википедии:

Есть несколько дочерних файлов заголовков, которые автоматически включаются в windows.h . Многие из этих файлов нельзя просто включить сами по себе (они не автономный) из-за зависимостей.

windef.h является одним из файлов, автоматически включенных в windows.h .

Я думал об этом, но не мог представить, что вы не включили windows.h. — engf-010

windows.h определяет группы других определений на основе переключателей компилятора и включает множество WINAPI-заголовков, некоторые из которых зависят от вещей, определенных windows.h. — engf-010

поздравляю, вы устранили свою проблему и у вас достаточно репутации, чтобы проголосовать! — Дэвид Хеффернан

Ни windows.h, ни windowsx.h (я предполагаю, что это одно и то же, но все равно пробовали оба), не помогают с этим #error Hey man you gotta choose a target. . Что еще можно исправить? — rsethc

Внимание: похоже, включает Xinput.h до того, как Windows.h тоже вызывает это. — Йенс Окерблом

Другой причиной этого может быть включение заголовка, который зависит от windows.h , прежде чем включать windows.h .

В моем случае я включил xinput.h до windows.h и получил эту ошибку. Смена порядка решила проблему.

Именно мое решение! Спасибо, что сэкономили мне часы разочарования. — Кислый9

Решите эту проблему, разместив сначала следующие включаемые файлы и определение:

Создан 18 июля ’19, 13:07

Это исправило мои сборки x86 и x64. Мне нужно было добавить эти строки раньше #include . — Джонатан Лидбек

Это сработало для меня (VS 2019, 32 бит) — ФракталКосмос

Если вы используете Resharper, убедитесь, что он не добавляет неправильный заголовок для вас, очень распространенные случаи с ReSharper:

Источник

When I try to compile my c++ project using Visual Studio 2010 in either Win32 or x64 mode I get the following error:

>C:Program Files (x86)Microsoft SDKsWindowsv7.0Aincludewinnt.h(135): fatal error C1189: #error : "No Target Architecture"

My preprocessor definitions say WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)

What is causing this error and how do I fix it?

// winnt.h: lines 127-136, MSVS says this is an inactive preprocessor block
#if defined(_WIN64)

#if defined(_AMD64_)
#define PROBE_ALIGNMENT( _s ) TYPE_ALIGNMENT( DWORD )
#elif defined(_IA64_)
#define PROBE_ALIGNMENT( _s ) (TYPE_ALIGNMENT( _s ) > TYPE_ALIGNMENT( DWORD ) ? 
                              TYPE_ALIGNMENT( _s ) : TYPE_ALIGNMENT( DWORD ))
#else
#error "No Target Architecture"
#endif

Update: I created a new msvs project and copied my code to it. I no longer have error : "No Target Architecture", but now I have a bunch of compile errors involving winnt.h and winbase.h and no compile errors involving any of my files. Is it possible these files are corrupted? Do I need to reinstall MSVS 2010?

Update 2: So I narrowed down my problem and found that it is #include <WinDef.h> that is causing all of my compile errors with winnt.h but I still don’t know how to fix it.

1) Solution

Use #include <windows.h> instead of #include <windef.h>.

From the windows.h (http://en.wikipedia.org/wiki/Windows.h) wikipedia page:

There are a number of child header files that are automatically included with windows.h. Many of these files cannot simply be included by themselves (they are not self-contained), because of dependencies.

windef.h is one of the files automatically included with windows.h.

2) Solution

Another cause of this can be including a header that depends on windows.h, before including windows.h.

In my case I included xinput.h before windows.h and got this error. Swapping the order solved the problem.

3) Solution

Solve it by placing the following include files and definition first:

#define WIN32_LEAN_AND_MEAN      // Exclude rarely-used stuff from Windows headers

#include <windows.h>
4) Solution

If you are using Resharper make sure it does not add the wrong header for you, very common cases with ReSharper are:

  • #include <consoleapi2.h
  • #include <apiquery2.h>
  • #include <fileapi.h>

UPDATE:
Another suggestion is to check if you are including a «partial Windows.h», what I mean is that if you include for example winbase.h or minwindef.h you may end up with that error, add «the big» Windows.h instead. There are also some less obvious cases that I went through, the most notable was when I only included synchapi.h, the docs clearly state that is the header to be included for some functions like AcquireSRWLockShared but it triggered the No target architecture, the fix was to remove the synchapi.h and include «the big» Windows.h.

The Windows.h is huge, it defines macros(many of them remove the No target arch error) and includes many other headers. In summary, always check if you are including some header that could be replaced by Windows.h because it is not unusual to include a header that relies on some constants that are defined by Windows.h, so if you fail to include this header your compilation may fail.

5) Solution

_WIN32 identifier is not defined.

use #include <SDKDDKVer.h>

MSVS generated projects wrap this include by generating a local "targetver.h"which is included by "stdafx.h" that is comiled into a precompiled-header through "stdafx.cpp".

EDIT : do you have a /D «WIN32» on your commandline ?

6) Solution

It would seem that _AMD64_ is not defined, since I can’t imagine you are compiling for Itanium (_IA64_).

7) Solution

I had a similar problem. In my case, I had accidentally included winuser.h before windows.h (actually, a buggy IDE extension had added it). Removing the winuser.h solved the problem.

8) Solution

At the beginning of the file you are compiling, before any include, try to put ONE of these lines

#define _X86_
#define _AMD64_
#define _ARM_

Choose the appropriate, only one, depending on your architecture.

9) Solution

Besides causes described already, I received this error because I’d include:

#include <fileapi.h>

Apparently it was not needed (despite of CreateDirectoryW call). After commenting out, compiler was happy. Very strange.

10) Solution

windows 10×64 pro build 19044.1586

My case was in order of .h files

Like this is dosen’t work

#include <processthreadsapi.h>
#include <iostream>
#include <windows.h>

But works like this

#include <windows.h>
#include <iostream>
#include <processthreadsapi.h>
11) Solution

Another reason for the error (amongst many others that cropped up when changing the target build of a Win32 project to X64) was not having the C++ 64 bit compilers installed as noted at the top of this page.
Further to philipvr’s comment on child headers, (in my case) an explicit include of winnt.h being unnecessary when windows.h was being used.

12) Solution

for me I was using glfw and imgui, and I included this header file by mistake:

#include <stringapiset.h>

I just removed it and this error no longer

13) Solution

If you want to avoid explicitly including a specific Windows SDK header, then something like this should work:

#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64)
#define _AMD64_
#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(__i386__) || defined(_M_IX86)
#define _X86_
#elif defined(__arm__) || defined(_M_ARM) || defined(_M_ARMT)
#define _ARM_
#endif
14) Solution

If you are building 32bit then make sure you don’t have _WIN64 defined for your project.

Comments Section

How do I set the target architecture for my project?

A vanilla project doesn’t fail this way. What have you changed from a vanilla project? What is at line 135 of winnt.h? Have you even looked at that line of the header file. The error message is giving you some help.

you should be able to work it out from here; probably need to go back before line 127 though to get the full picture. It would seem clear that Edwin was correct.

Try a new msvs project (dummy) and copy-drag your sources into it. Try to compile it and if it does ,compare it with your original project. BTW don’t copy the stdafx.*

Should it be _WIN32 rather than WIN32? It’s not my area of expertise, but given that the header is looking for _WIN64, ‘_AMD64_` etc. it would seem plausible.

@David Heffernan : at the commandline it says WIN32 (no _) even for x84. Don’t know the rationale of it (but who does understand MS)

@Edwin x84? Is that George Orwell’s computer?

@David Heffernan: yes ,big brother is watching me ! (obviously x64 i meant)

AMD64 will be defined under some conditions:#if !defined(68K) && !defined(MPPC) && !defined(X86) && !defined(IA64) && !defined(AMD64) && defined(_M_AMD64)

@Edwin If _AMD64_ or _IA64_ was defined, then he wouldn’t be getting the error. That’s what the header file says.

Does sound bad. But before you do a re-install ,you first could try it with a new solution and if that doesn’t work you can manualy re-install project=templates (google it).

philipvr has updated his post. He has other (more) problems. He’s thinking re-install MSVS.

I did think of that ,but I couldn’t imaging that you didn’t include windows.h.

windows.h defines alkinds of other defines based on compiler-switches and includes many WINAPI-headers ,some of which depending on things defned by windows.h.

congratulations, you have fixed your problem and you have enough rep to vote up!

Neither windows.h not windowsx.h (I assume them to be the same thing but have tried both anyway) help with that #error Hey man you gotta choose a target.. What else could fix that?

Exactly my solution! Thanks for saving me hours of frustration.

If I include Windows.h I get told that I cannot include it twice. Why doesn’t it just ignore the second inclusion?

Another visit to this page arose when an old project happened to have ` #include <synchapi.h>` in a CriticalSection header.

In my case _WIN32 was defined and was the culprit. I was building for x64. Your answer put me on track. Good job!

For me ReSharper added consoleapi2.h

This fixed both my x86 and x64 builds. I needed to add these lines before #include <WinUser.h>.

I have exactly the same situation.

Thank you. I include windows.h to replace WinBase.h and fileapi.h.

Related Topics
windows
visual-c++
c++
visual-studio
compiler-errors

Mentions
Brian
Mx Nx
Shital Shah
David Heffernan
Andrea Araldo
A T
Melardev
Nathan Reed
Michael Haephrati
Philipvr
The Oathman
Laurie Stearn

References
4845198/fatal-error-no-target-architecture-in-visual-studio

Geeks, please accept the hero post of 2021 Microsoft x Intel hacking contest>>>

Root cause:

This is because it contains some header files that windows. H already contains, such as “fileapi. H” and “winuser. H”, but it does not contain windows. H
or
it contains “fileapi. H” and “winuser. H” first, and then contains windows. H, which is not in the right order

Let’s start with the solution:

just add include “windows. H” to the code, or adjust the order and put winows. H in front of it or

Online solutions:

Add to project_ AMD64_ Macro (the other three can also be used) can also solve the problem
specific method: right click the project name — > Attribute — > C/C++–> Preprocessor — > Add a macro as follows:

specific process:

When I call the shellexecute function, I will prompt the error “no target architecture”. The code is simplified as follows:

#include "stdafx.h"
#include "WinUser.h"
#include <ShellAPI.h>
int main()
{
    ShellExecute(0, NULL, L"http://www.baidu.com", NULL, NULL, SW_SHOWNORMAL);
    return 0;
}

The location error is in WinNT. H

#if defined(_AMD64_) || defined(_X86_)
#define PROBE_ALIGNMENT( _s ) TYPE_ALIGNMENT( DWORD )
#elif defined(_IA64_) || defined(_ARM_) || defined(_ARM64_)

#define PROBE_ALIGNMENT( _s ) TYPE_ALIGNMENT( DWORD )
#elif !defined(RC_INVOKED)
#error "No Target Architecture"
#endif

The reason is that there is no definition of (_ AMD64_) 、(_ X86_) When the compiler detects these macros, it throws an exception

When shellexecute is called, SW_ Show normal prompt can’t be found, check, SW_ Shownormal is defined in “winuser. H”, so “include” winuser. H “

“Winuser. H” defines all API exported by user32.dll and various macro definitions, such as WM representing message ID_* Macro, most of the APIs related to windows UI are defined in winuser. H. This file is included in windows. H

So it’s usually direct include & lt; windows.h> As mentioned above (_ AMD64_) 、(_ X86_) It was also defined in windows. H first, so an error was reported

In this case, winuser and & lt; ShellAPI.h> Can be deleted, including a windows. H can be directly

What are the important header files in windows. H:

Windows. H is one of the most important header files. It contains other windows header files, some of which also contain other header files. The most important and basic of these header files are:

Windef. H basic data type definition
WinNT. H supports Unicode type definition
winbase. H kernel function
winuser. H user interface function// in this example, shellexecute is defined here
wingdi. H graphic device interface function



когда я пытаюсь скомпилировать свой проект c++ с помощью Visual Studio 2010 в режиме Win32 или x64, я получаю следующую ошибку:

>C:Program Files (x86)Microsoft SDKsWindowsv7.0Aincludewinnt.h(135): fatal error C1189: #error : "No Target Architecture"

мои определения препроцессора говорят WIN32; _DEBUG; _CONSOLE;%(PreprocessorDefinitions)

что вызывает эту ошибку и как это исправить?

// winnt.h: lines 127-136, MSVS says this is an inactive preprocessor block
#if defined(_WIN64)

#if defined(_AMD64_)
#define PROBE_ALIGNMENT( _s ) TYPE_ALIGNMENT( DWORD )
#elif defined(_IA64_)
#define PROBE_ALIGNMENT( _s ) (TYPE_ALIGNMENT( _s ) > TYPE_ALIGNMENT( DWORD ) ?
TYPE_ALIGNMENT( _s ) : TYPE_ALIGNMENT( DWORD ))
#else
#error "No Target Architecture"
#endif

обновление: я создал новый проект msvs и скопировал в него свой код. У меня больше нет error : "No Target Architecture", но теперь у меня есть куча ошибок компиляции с участием winnt.h и winbase.h И никаких ошибок компиляции, связанных с любым из моих файлов. Возможно ли, что эти файлы повреждены? Нужно ли переустановить MSVS 2010?

обновление 2: поэтому я сузил свою проблему и обнаружил, что это #include <WinDef.h> это вызывает все мои ошибки компиляции с winnt.но я все еще не знаю, как это исправить.


810  


9  

9 ответов:

использовать #include <windows.h> вместо #include <windef.h>.

С windows.h Википедии страницы:

есть несколько дочерних заголовочных файлов, которые автоматически включаются в windows.h. Многие из этих файлов не могут быть просто включены сами по себе (они не автономного), из-за зависимостей.

windef.h является одним из файлов, автоматически включенных в windows.h.

еще одна причина этого может быть в том числе заголовок, который зависит от windows.h, перед windows.h.

в моем случае я включил xinput.h до windows.h и получил эту ошибку. Замена заказа решила проблему.

идентификатор _WIN32 не определен.

использовать #include <SDKDDKVer.h>

MSVS генерируемые проекты обернуть это включает в себя путем создания локального "targetver.h", который включен "stdafx.h" это комилируется в предварительно скомпилированный заголовок через "stdafx.cpp".

EDIT: у вас есть A /D «WIN32» в командной строке ?

казалось бы _AMD64_ не определено, так как я не могу себе представить, что вы компилируете для Itanium (_IA64_).

Если вы строите 32bit, то убедитесь, что у вас нет _WIN64, определенного для вашего проекта.

еще одна причина ошибки (среди многих других, которые возникли при изменении целевой сборки проекта Win32 на X64) не было установлено 64-разрядных компиляторов C++, как указано в верхней части на этой странице.
В дополнение к комментарию philipvr о дочерних заголовках (в моем случае) явное включение winnt.h будучи лишних, когда windows.h используется.

у меня была похожая проблема. В моем случае, я случайно включил winuser.h до windows.h (на самом деле, расширение багги IDE добавил его). Удаление winuser.h решена проблема.

помимо уже описанных причин, я получил эту ошибку, потому что я бы включил:

#include <fileapi.h>

видимо это было не нужно (несмотря на CreateDirectoryW вызова). После комментирования, компилятор был счастлив. Очень странный.

c

#c #Windows #visual-studio #visual-c #ошибки компилятора

Вопрос:

Когда я пытаюсь скомпилировать свой проект на c с использованием Visual Studio 2010 в режиме Win32 или x64, я получаю следующую ошибку:

>C:Program Files (x86)Microsoft SDKsWindowsv7.0Aincludewinnt.h(135): fatal error C1189: #error : "No Target Architecture"

В моих определениях препроцессора указано WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)

Что вызывает эту ошибку и как мне ее исправить?

 // winnt.h: lines 127-136, MSVS says this is an inactive preprocessor block
#if defined(_WIN64)

#if defined(_AMD64_)
#define PROBE_ALIGNMENT( _s ) TYPE_ALIGNMENT( DWORD )
#elif defined(_IA64_)
#define PROBE_ALIGNMENT( _s ) (TYPE_ALIGNMENT( _s ) > TYPE_ALIGNMENT( DWORD ) ? 
                              TYPE_ALIGNMENT( _s ) : TYPE_ALIGNMENT( DWORD ))
#else
#error "No Target Architecture"
#endif
 

Обновление: я создал новый проект msvs и скопировал в него свой код. У меня больше нет error : "No Target Architecture" , но теперь у меня есть куча ошибок компиляции, связанных с winnt.h и winbase.h, и никаких ошибок компиляции, связанных с любым из моих файлов. Возможно ли, что эти файлы повреждены? Нужно ли мне переустановить MSVS 2010?

Обновление 2: Итак, я сузил круг своих проблем и обнаружил, что именно #include <WinDef.h> это вызывает все мои ошибки компиляции с помощью winnt.h, но я все еще не знаю, как это исправить.

Комментарии:

1. Как мне установить целевую архитектуру для моего проекта?

2. Ванильный проект не завершается таким образом. Что вы изменили по сравнению с ванильным проектом? Что находится в строке 135 winnt.h? Вы хотя бы смотрели на эту строку заголовочного файла? Сообщение об ошибке дает вам некоторую помощь.

3. вы должны быть в состоянии решить это отсюда; вероятно, нужно вернуться к строке 127, чтобы получить полную картину. Казалось бы, ясно, что Эдвин был прав.

4. Попробуйте новый проект msvs (фиктивный) и скопируйте в него свои исходные тексты. Попробуйте скомпилировать его, и если это произойдет, сравните его с вашим исходным проектом. Кстати, не копируйте stdafx.*

5. Звучит плохо. Но прежде чем выполнять переустановку, вы сначала можете попробовать это с новым решением, и если это не сработает, вы можете вручную переустановить project=templates (google it).

Ответ №1:

Используйте #include <windows.h> вместо #include <windef.h> .

Со страницы windows.h википедии:

Существует несколько дочерних заголовочных файлов , которые автоматически включаются в windows.h состав . Многие из этих файлов не могут быть просто включены сами по себе (они не являются автономными) из-за зависимостей.

windef.h является одним из файлов, автоматически включенных в windows.h .

Комментарии:

1. Я действительно думал об этом, но я не мог представить, что вы не включили windows.h.

2. windows.h определяет множество других определений на основе переключателей компилятора и включает в себя множество заголовков WINAPI, некоторые из которых зависят от вещей, определенных windows.h.

3. поздравляем, вы устранили проблему, и у вас достаточно репутации, чтобы проголосовать!

4. Ни windows.h, ни windowsx.h (я предполагаю, что это одно и то же, но все равно пробовал оба варианта) не помогают в этом #error Hey man you gotta choose a target. . Что еще может это исправить?

5. Если я включу Windows. h Мне говорят, что я не могу включить его дважды. Почему он просто не игнорирует второе включение?

Ответ №2:

Другой причиной этого может быть включение заголовка, который зависит от windows.h , перед включением windows.h .

В моем случае я включил xinput.h before windows.h и получил эту ошибку. Замена порядка решила проблему.

Комментарии:

1. Именно мое решение! Спасибо, что избавили меня от часов разочарования.

Ответ №3:

Решите ее, поместив сначала следующие включаемые файлы и определение:

 #define WIN32_LEAN_AND_MEAN      // Exclude rarely-used stuff from Windows headers

#include <windows.h>
 

Комментарии:

1. Это исправило обе мои сборки x86 и x64. Мне нужно было добавить эти строки раньше #include <WinUser.h> .

Ответ №4:

Если вы используете Resharper, убедитесь, что он не добавляет неправильный заголовок для вас, очень распространенные случаи с ReSharper:

  • #include <consoleapi2.h
  • #include <apiquery2.h>
  • #include <fileapi.h>

ОБНОВЛЕНИЕ:
еще одно предложение — проверить, включаете ли вы «частичный Windows.h», я имею в виду, что если вы включите, например, winbase.h или minwindef.h, вы можете столкнуться с этой ошибкой, вместо этого добавьте «большой» Windows.h. Есть также несколько менее очевидных случаев, с которыми я столкнулся, наиболее заметным было, когда я включил только synchapi.h, в документах четко указано, что это заголовок, который должен быть включен для некоторых функций, таких как AcquireSRWLockShared, но это вызвало отсутствие целевой архитектуры, исправление заключалось в удалении synchapi.h и включении «большой » Windows.h.

Windows.h огромен, он определяет макросы (многие из них удаляют ошибку No target arch) и включает в себя множество других заголовков. В заключение, всегда проверяйте, включаете ли вы какой-либо заголовок, который может быть заменен Windows.h, потому что нет ничего необычного в том, чтобы включать заголовок, который зависит от некоторых констант, определенных Windows.h , поэтому, если вы не включите этот заголовок, ваша компиляция может завершиться неудачно.

Комментарии:

1. Спасибо. Я включаю windows.h для замены WinBase.h и fileapi.h .

Ответ №5:

Идентификатор _WIN32 не определен.

используйте #include <SDKDDKVer.h>

Проекты, сгенерированные MSV, завершают это включение, генерируя локальный "targetver.h" файл, который включен, "stdafx.h" который включен в предварительно скомпилированный заголовок "stdafx.cpp" .

РЕДАКТИРОВАТЬ: есть ли у вас a / D «WIN32» в вашей командной строке?

Комментарии:

1. Должно ли это быть _WIN32 , а не WIN32 ? Это не моя область знаний, но, учитывая, что заголовок ищет _WIN64 , «_AMD64_` и т. Д. это казалось бы правдоподобным.

2. @David Heffernan: в командной строке написано WIN32 (no _) даже для x84. Не знаю причины этого (но кто понимает MS)

3. @Edwin x84? Это компьютер Джорджа Оруэлла?

4. @Дэвид Хеффернан: да, большой брат следит за мной ! (очевидно, я имел в виду x64)

5. В моем случае _WIN32 был определен и был виновником. Я строил для x64. Ваш ответ поставил меня на правильный путь. Хорошая работа!

Ответ №6:

Казалось бы, это _AMD64_ не определено, поскольку я не могу представить, что вы компилируете для Itanium ( _IA64_ ).

Комментарии:

1. AMD64 будет определен при некоторых условиях: #if !определено ( 68K ) amp;amp; !определено ( MPPC ) amp;amp; !определено ( X86 ) amp;amp; !определено ( IA64 ) amp;amp; !определено ( AMD64 ) amp;amp; определено (_M_AMD64)

2. @Edwin Если _AMD64_ _IA64_ был определен or , то он не получал бы ошибку. Это то, что говорится в заголовочном файле.

3. philipvr обновил свой пост. У него другие (больше) проблемы. Он думает переустановить MSVS.

Ответ №7:

У меня была похожая проблема. В моем случае я случайно включил winuser.h раньше windows.h (на самом деле, его добавило ошибочное расширение IDE). Удаление winuser.h решило проблему.

Комментарии:

1. Для меня добавлен ReSharper consoleapi2.h

Ответ №8:

В начале файла, который вы компилируете, перед любым include , попробуйте поместить ОДНУ из этих строк

 #define _X86_
#define _AMD64_
#define _ARM_
 

Выберите подходящий, только один, в зависимости от вашей архитектуры.

Ответ №9:

Помимо уже описанных причин, я получил эту ошибку, потому что я бы включил:

 #include <fileapi.h>
 

По-видимому, это не понадобилось (несмотря на вызов CreateDirectoryW). После комментирования компилятор был доволен. Очень странно.

Комментарии:

1. У меня точно такая же ситуация.

Ответ №10:

windows 10×64 pro сборка 19044.1586

Мой случай был в порядке файлов .h

Как будто это не работает

 #include <processthreadsapi.h>
#include <iostream>
#include <windows.h>
 

Но работает так

 #include <windows.h>
#include <iostream>
#include <processthreadsapi.h>
 

Ответ №11:

Другой причиной ошибки (среди многих других, возникших при изменении целевой сборки проекта Win32 на X64) было отсутствие установленных 64-разрядных компиляторов C , как указано в верхней части этой страницы.
В дополнение к комментарию philipvr о дочерних заголовках (в моем случае) явное включение winnt.h было ненужным при использовании windows.h .

Комментарии:

1. Еще одно посещение этой страницы возникло, когда в старом проекте случайно оказалось `#include <synchapi.h>` в заголовке CriticalSection .

Ответ №12:

Если вы создаете 32-битную версию, убедитесь, что для вашего проекта не определен _WIN64.

Ответ №13:

Если вы хотите избежать явного включения определенного заголовка Windows SDK, то должно сработать что-то вроде этого:

 #if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64)
#define _AMD64_
#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(__i386__) || defined(_M_IX86)
#define _X86_
#elif defined(__arm__) || defined(_M_ARM) || defined(_M_ARMT)
#define _ARM_
#endif
 

Ответ №14:

для меня я использовал glfw и imgui, и я по ошибке включил этот файл заголовка:

 #include <stringapiset.h>
 

Я просто удалил ее, и эта ошибка больше не

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error c1083 не удается открыть файл включение stdio h no such file or directory
  • Fatal error c1083 не удается открыть файл включение stdafx h
  • Fatal error c1083 не удается открыть файл включение pthread h no such file or directory
  • Fatal error c1083 не удается открыть файл включение math h
  • Fatal error c1083 не удается открыть файл включение crtdbg h no such file or directory

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

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