Fatal error lnk1112 module machine type x86 conflicts with target machine type x64

I'm using CUDA (VC++, Visual studio 2008sp1) to debug a FEM program. The program can only run on a Win32 platform, for the insufficiency of cuda. I think the library files linked are all compiled o...

I’m using CUDA (VC++, Visual studio 2008sp1) to debug a FEM program. The program can only run on a Win32 platform, for the insufficiency of cuda. I think the library files linked are all compiled on the x86 platform, but when I compile it, I get the error message

fatal error LNK1112: module machine type ‘x64’ conflicts with target machine type ‘X86’.

I have tried to convert the platform to x64, but it didn’t work. Please tell me: what is «module machine type» and what is «target machine type»? How can I overcome it?

Jarod42's user avatar

Jarod42

198k13 gold badges178 silver badges288 bronze badges

asked Aug 25, 2010 at 7:36

user430382's user avatar

I wrote a blog entry about this, as I encountered this maddening problem, and finally yanked my system back into working order.

These are the things to check, in this order:

  1. Check your properties options in your linker settings at: Properties > Configuration Properties > Linker > Advanced > Target Machine. Select MachineX64 if you are targeting a 64 bit build, or MachineX86 if you are making a 32 bit build.

  2. Select Build > Configuration Manager from the main menu in visual studio. Make sure your project has the correct platform specified. It is possible for the IDE to be set to build x64 but an individual project in the solution can be set to target win32. So yeah, visual studio leaves a lot of rope to hang yourself, but that’s life.

  3. Check your library files that they really are of the type of platform are targeting. This can be used by using dumpbin.exe which is in your visual studio VCbin directory. use the -headers option to dump all your functions. Look for the machine entry for each function. it should include x64 if it’s a 64 bit build.

  4. In visual studio, select Tools > Options from the main menu. select Projects and Solutions > VC++ Directories. Select x64 from the Platform dropdown. Make sure that the first entry is: $(VCInstallDir)binx86_amd64 followed by $(VCInstallDir)bin.

Once I did step 4 everything worked again for me. The thing was I was encountering this problem on all my projects where I wanted to compile towards a 64 bit target.

Sep's user avatar

Sep

3373 silver badges12 bronze badges

answered Dec 6, 2010 at 7:06

C.J.'s user avatar

C.J.C.J.

15.5k9 gold badges60 silver badges77 bronze badges

13

In addition to C Johnson list I would add the following point:

Check in Visual Studio:
Project Properties -> Configuration Properties -> Linker -> Command line.

«Additional Options» should NOT contain /machine:X86

I have such key, generated by CMake output: CMake generated x86 project, then I added x64 platform via Configuration Manager in Visual Studio 2010 — everything was created fine for the new platform except that the linker command line, specified /machine:X86 separately.

Heyji's user avatar

Heyji

1,0838 silver badges26 bronze badges

answered Apr 8, 2013 at 22:35

sergtk's user avatar

sergtksergtk

10.5k15 gold badges75 silver badges129 bronze badges

6

I experienced the same problem in VS2008 when I tried to add a X64 build to a project converted from VS2003.

I looked at everything found when searching for this error on Google (Target machine, VC++Directories, DUMPBIN….) and everything looked OK.

Finally I created a new test project and did the same changes and it seemed to work.

Doing a diff between the vcproj files revealed the problem….

My converted project had /MACHINE:i386 set as additional option set under Linker->Command Line. Thus there was two /MACHINE options set (both x64 and i386) and the additional one took preference.

Removing this and setting it properly under Linker->Advanced->Target Machine made the problem disappeared.

CassOnMars's user avatar

CassOnMars

6,1432 gold badges33 silver badges46 bronze badges

answered Jan 13, 2012 at 8:28

Zid's user avatar

ZidZid

5614 silver badges2 bronze badges

2

All project settings seemed perfect, but I still got the error. Looking into the .vcxproj file and searching for «x86» revealed the problem:

<Lib>
  <AdditionalOptions> /machine:X86 %(AdditionalOptions)</AdditionalOptions>
</Lib>

A quick search/replace for all occurrances (ten individual file settings) fixed the problem.

answered Mar 13, 2017 at 20:20

kungfooman's user avatar

kungfoomankungfooman

4,2271 gold badge42 silver badges30 bronze badges

2

You probably have one .OBJ or .LIB file that’s targeted for x64 (that’s the module machine type) while you’re linking for x86 (that’s the target machine type).

Use DUMPBIN /HEADERS on your .OBJ files and check for the machine entry in the FILE HEADER VALUES block.

answered Aug 25, 2010 at 8:01

Patrick's user avatar

PatrickPatrick

23k11 gold badges66 silver badges129 bronze badges

2

Since the problem is due to the difference in compilation and target machine specifications (x86 & x64)
Follow the steps below:

  1. Open the C++ project that you want to configure.
  2. Choose the Configuration Manager button to open the Configuration Manager dialog box.
  3. In the Active Solution Platform drop-down list, select the option to open the New Solution Platform dialog box.
  4. In the Type or select the new platform drop-down list, select a 64-bit platform.

It solved my problem.

answered May 13, 2014 at 20:55

hab's user avatar

habhab

6172 gold badges8 silver badges20 bronze badges

In Visual Studio 2012 +/-, the property page for «Configuration Properties’.Linker.»Command Line» contains a box labeled «Additional Options». If you’re building x64, make sure that box doesn’t contain /MACHINE:I386. My projects did and it generated the error in question.

answered Nov 15, 2014 at 4:59

laloumen's user avatar

laloumenlaloumen

1,1891 gold badge13 silver badges15 bronze badges

0

I came across this problem when building QT. The instructions I read somewhere suggested that I configure nmake using VS command prompt.

I chose the x64 command prompt and performed configure without much hassle. When i tried nmake, it gave this error.

I think some of the components were pre-built for 32-bit. The error even reported which modules were built for x86.

I used the 32 bit default VS command prompt and it worked.

Trevor Hickey's user avatar

Trevor Hickey

35.5k28 gold badges153 silver badges263 bronze badges

answered Aug 29, 2013 at 9:52

pvairam's user avatar

1

"project property - CUDA Runtime API - GPU - NVCC Compilation Type"

Set the 64 bit compile option -m64 -cubin

The hint is at compile log.
Like this:

nvcc.exe ~~~~~~ -machine 32 -ccbin ~~~~~

That "-machine 32" is problem.

First set 64bit compile option,
next re setting hybrid compile option.
Then u can see the succeed.

Zaheer Ahmed's user avatar

Zaheer Ahmed

28k11 gold badges73 silver badges110 bronze badges

answered Jul 25, 2013 at 10:34

chang's user avatar

changchang

311 bronze badge

1

In Visual Studio 2013,

1) Check in the Project Property Pages / Configuration Properties / Linker / All Options and correct all the miss configured machine and directories.

2) Check in the Project Property Pages / Configuration Properties / Linker / Input and correct all the miss configured directories.

See example of 1)

shriek's user avatar

shriek

5,1472 gold badges35 silver badges42 bronze badges

answered Jan 3, 2014 at 17:43

Fabrício Ceolin's user avatar

If your solution has lib projects check Target Machine property in Property->Librarian->General

answered Oct 28, 2013 at 9:47

Rinat's user avatar

RinatRinat

212 bronze badges

0

vcxproj file may contain ‘MACHINE:i386’
Edit vcxproj file with editor. remove it !

answered Sep 29, 2017 at 2:00

Mark Yang's user avatar

Mark YangMark Yang

2203 silver badges16 bronze badges

My target is a x64 Windows 10 text mode DOSBox application in C language.
Using «Visual Studio 2019 Community» to compile through DOS prompt «nmake -f makefile».
The error is similar but on the opposite side:

fatal error LNK1112: module machine type 'x32' conflicts with target machine type 'X64'

It’s ok to compile by VC++ 2010 on another computer. But failed on this computer by «Visual Studio 2019 Community». So my settings are correct and all above answers do not work.

I’d like to share you that the solution is a make.bat like this:

call "c:Program Files (x86)Microsoft Visual Studio2019CommunityVCAuxiliaryBuildvcvars64.bat" 
nmake -f makefile

You will find there are many other vcvarsxxxx.bat, only this one words.

answered Oct 10, 2020 at 0:01

H.C.Chen's user avatar

H.C.ChenH.C.Chen

4124 silver badges14 bronze badges

In addition to Jhonson’s list, also check library’s folders

In visual studio, select Tools > Options from the main menu. select Projects and Solutions > VC++ Directories. Select x64 from the Platform dropdown.

$(VCInstallDir)libAMD64;
$(VCInstallDir)atlmfclibamd64;
$(WindowsSdkDir)libx64;

answered Jan 13, 2014 at 15:55

Igor Barbarian's user avatar

0

This happened to me today because I had added a library directory while still in x86 mode, and accidently removed the inherited directories, making them hardcoded instead.
Then after switching to x64, my VC++ Directories still read:

«…;$(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);»

instead of the _x64.

answered Oct 17, 2015 at 18:41

masterxilo's user avatar

masterxilomasterxilo

2,3741 gold badge29 silver badges34 bronze badges

1

I was using CMake & then added a win32 configuration. The property page showed x86 but actually when opening the vcxproj file in a text editor it was x64! Manually changing to x86 solved this.

answered Jan 31, 2016 at 17:44

grunt's user avatar

gruntgrunt

6521 gold badge7 silver badges24 bronze badges

1

First of all try the following things:
1. goto configuration Manager and create a new x64 if it is not already there.
2. select the x64 solution.
3. go to project properties and then Linker->Advanced select x64 machine.
4. Now rebuild the solution.

If still you are getting the same error. try clean solution and then rebuild again and open visual studio you will get list of recent opened project , right click on the project and remove it from there. Now go to the solution and reopen the solution again.

answered Jun 2, 2016 at 11:05

It’s a very frustrating and annoying problem but once you understand it, it’s quite simple: you have some element in you’re build that building one architecture type (in your case x64) despite the fact that it’s been target for another type (say x86).

You can dissect the source of your problem by looking at which obj file is causing the crash and start looking for the problem there. Every obj will have a source code analog: either in cpp, c, asm etc. There may be special build events around it that are using the wrong tool. Check for that in the property sheets.

I’d look there first before going through C Johnson list of things to do.

answered Jan 28, 2017 at 21:34


I solved this problem by changing Win32 to *64 in Visual Studio 2013.

answered Aug 8, 2018 at 9:44

Salman Saleh's user avatar

Many good suggestions above.

Also if you are trying to build in x86 Win32:

Make sure that any libraries you link to in Program Files(x86) are actually x86 libraries because they are not necessarily…

For example a lib file I linked to in C:Program Files (x86)Microsoft Visual Studio2019ProfessionalSDK threw that error, eventually I found an x86 version of it in C:Program Files (x86)Windows Kits10Lib10.0.18362.0umx86 and everything worked fine.

answered Jan 9, 2020 at 15:28

GrahamJ's user avatar

GrahamJGrahamJ

5184 silver badges15 bronze badges

Properties->configurationManager-> ActiveSolutionPlatform . Here select x64 .thats all.

It should take care of all dependencies and compilation should work smoothly

answered Jan 19, 2022 at 6:28

user265906's user avatar

user265906user265906

1001 silver badge8 bronze badges

module machine type is the machine on which you are compiling and the target machine type is the the architecture x86 or x64 for which you are building your binaries.

answered Oct 16, 2013 at 4:40

djs's user avatar

This problem may also happen if your project set up to have the same intermediate directories in Project Properties -> Configuration Properties -> General

answered Jun 6, 2015 at 17:03

Anton K's user avatar

Anton KAnton K

4,5822 gold badges48 silver badges59 bronze badges

this happens to me when i convert my VS2008 solution to VS2010 & change win32 configuration to X64, in my old solution I have mfcs90d.lib (Configuration->Linker->Input->Additional dependencies), as I am using VS010 i just checked in VS2010 folder where it is mfcs100d.lib, so I changed mfcs90d.lib to mfcs100d.lib in (Configuration->Linker->Input->Additional dependencies) it worked fine.

answered Mar 2, 2017 at 9:03

NDestiny's user avatar

NDestinyNDestiny

1,1031 gold badge11 silver badges28 bronze badges

For those who are with QT Creator, the issue is same (as described by @c-johnson).
Make sure the compiler settings for MSVC in your kit is set to x86 as shown below.

QT Creator Kit Settings for MSVC x86 compiler

answered Jul 9, 2019 at 15:41

Jimson James's user avatar

Jimson JamesJimson James

2,5926 gold badges39 silver badges69 bronze badges

for some using command prompt (dos prompt)
this might be helpful:

call "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" --help
Error in script usage. The correct usage is:
    "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" [option]
  or
    "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" [option] store
  or
    "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" [option] [version number]
  or
    "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" [option] store [version number]
where [option] is: x86 | amd64 | arm | x86_amd64 | x86_arm | amd64_x86 | amd64_arm
where [version number] is either the full Windows 10 SDK version number or "8.1" to use the windows 8.1 SDK
:
The store parameter sets environment variables to support
  store (rather than desktop) development.
:
For example:
    "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" x86_amd64
    "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" x86_arm store
    "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" x86_amd64 10.0.10240.0
    "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" x86_arm store 10.0.10240.0
    "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" x64 8.1
    "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" x64 store 8.1
:
Please make sure either Visual Studio or C++ Build SKU is installed.

Also If you do like this:

CL «%1%2%3» /EHsc /link user32.lib Gdi32.lib Winmm.lib comctl32.lib *.obj /SUBSYSTEM:CONSOLE /MACHINE:x86

you have to del *.obj before; to avoid confusing linker with both 64 and 32 bit objects left over from prior compilations?

answered Jul 29, 2019 at 1:30

kris2k's user avatar

kris2kkris2k

3053 silver badges5 bronze badges

I have fixed this problem for myself as follows.

First of all, I followed the other answers for this question, only to conclude that all the project settings were correct.

Then I inspected the .vcxproj file with an editor and noticed that the < Link > properties for the two (Debug and Release) x64 configurations did not specify < TargetMachine >, while the Win32 configurations both contained < TargetMachine > MachineX86 < /TargetMachine >.

However, I had already verified, looking from Visual Studio at Properties > Configuration Properties > Linker > Advanced > Target Machine, that the x64 configurations said MachineX64 (/MACHINE:X64).

So, I edited the .vcxproj file to include < TargetMachine > MachineX64 < /TargetMachine > in the two x64 configs. Going back to the Visual Studio project properties dialog, I noticed that the MachineX64 (/MACHINE:X64) setting was there as before, except that now it showed in bold (apparently meaning that the value is not the default one).

I rebuilt, and it worked.

answered Nov 2, 2020 at 8:30

user1752563's user avatar

I’ve read a lot of similar problems to mine, but none had a solution that helped. I’m building a program that runs the functions of a DLL. Everything compiled fine in 32 bit, but now that I’m tryign to compile for x64 I get a lot of errors.

I get the error in the title for the following libraries:
mfcs100.lib  msvcrt.lib  msvcprt.lib

I tried adding them to the ignored libraries list, but then got a large number of unresolved linker errors. The program I’m creating is using MFC in a Shared DLL, if that helps.

Any help would be greatly appreciated

(an example of my error output follows)

1>—— Rebuild All started: Project: SpellCheckTest, Configuration: Release x64 ——

1>Build started 7/11/2011 9:08:54 AM.

1>_PrepareForClean:

1> Deleting file «x64ReleaseSpellCheckTest.lastbuildstate».

1>InitializeBuildStatus:

1> Touching «x64ReleaseSpellCheckTest.unsuccessfulbuild».

1>ClCompile:

1> SpellCheckTest.cpp

1> stdafx.cpp

1>Link:

1>

1> Searching libraries

1> Searching SpellCheckUI.lib:

1> Searching C:Documents and SettingsMyNameDesktopcodeSpellCheckUI\Hunspellhunspell-1.2.14srcwin_apiDebug_dlllibhunspelllibhunspell.lib:

1> Searching C:Program FilesMicrosoft Visual Studio 10.0VCatlmfclibmfc100.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibkernel32.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibuser32.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibgdi32.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibmsimg32.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibcomdlg32.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibwinspool.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibadvapi32.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibshell32.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibcomctl32.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibshlwapi.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibuuid.lib:

1> Searching C:Program FilesMicrosoft Visual Studio 10.0VCatlmfclibatls.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibole32.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Aliboleaut32.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Aliboledlg.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Aliburlmon.lib:

1> Searching C:Program FilesMicrosoft SDKsWindowsv7.0Alibgdiplus.lib:

1> Searching C:Program FilesMicrosoft Visual Studio 10.0VClibcomsuppw.lib:

1> Searching C:Program FilesMicrosoft Visual Studio 10.0VClibmsvcprt.lib:

1>msvcprt.lib(MSVCP100.dll) : fatal error LNK1112: module machine type ‘X86’ conflicts with target machine type ‘x64’

1> 

1>Build FAILED.

1>

1>Time Elapsed 00:00:03.48

========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

0 / 0 / 0

Регистрация: 14.05.2013

Сообщений: 22

1

05.01.2014, 14:25. Показов 6053. Ответов 10


Всем привет. Ситуация такова. Решил значит ознакомится с VS и SFML. Скачал (как-бы грешно это не звучало) Visual studio 2010 и SFML 2.1 (Visual C++ 10 (2010) — 64 bits, т.к. у меня 64 разрядная система). После свершил некоторые деяния над VS по инструкции http://www.sfml-dev.org/tutorials/2.0/start-vc.php. Однако после запуска введенного кода (дабы лицезреть «зеленый кружек»), мне высвечивается ошибка «error LNK1112: module machine type ‘x64’ conflicts with target machine type ‘X86′». Почитал во всемогущем интернете про конфликт разрядности, увы, решения данной проблемы не нашел. Надеюсь, что помогут местные, знающие люди. Заранее благодарю.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



5493 / 4888 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

05.01.2014, 14:54

2

Разрядность проекта?



1



0 / 0 / 0

Регистрация: 14.05.2013

Сообщений: 22

05.01.2014, 15:15

 [ТС]

3

А где это можно глянуть? Коль не секрет.



0



5493 / 4888 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

05.01.2014, 15:20

4

Цитата
Сообщение от Trisane
Посмотреть сообщение

А где это можно глянуть?

Миниатюры

Visual studio 2010 и SFML 2.1, ошибка LNK1112
 



1



5493 / 4888 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

05.01.2014, 15:25

5

SFML какая: 32-х или 64-х битная?



1



0 / 0 / 0

Регистрация: 14.05.2013

Сообщений: 22

05.01.2014, 15:37

 [ТС]

6

SFML 64-х битная. В начале писал «SFML Visual C++ 10 (2010) — 64 bits, т.к. у меня 64 разрядная система».
Так у меня VS выглядит.

Миниатюры

Visual studio 2010 и SFML 2.1, ошибка LNK1112
 



0



0 / 0 / 0

Регистрация: 14.05.2013

Сообщений: 22

05.01.2014, 15:52

 [ТС]

7

Еще полазил в параметрах проекта, и нашел одну строчку. Однако даже после смены параметра на «MachineX64 (/MACHINE:X64)». Ошибка по прежнему появляется, только уже «error LNK1112: module machine type ‘X86’ conflicts with target machine type ‘x64′», то есть ‘x64’ и ‘x86’ поменялись местами.

Миниатюры

Visual studio 2010 и SFML 2.1, ошибка LNK1112
 



0



5493 / 4888 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

05.01.2014, 15:54

8

На скрине, в 6 посте, окно, там меняйте на x64 (Platform).



1



0 / 0 / 0

Регистрация: 14.05.2013

Сообщений: 22

05.01.2014, 15:58

 [ТС]

9

Все, заработало Огромное спасибо за помощь и терпение



0



0 / 0 / 1

Регистрация: 15.10.2015

Сообщений: 69

15.01.2017, 20:25

10

Up тему. дабы не создавать новой. Такая же проблема, только я поменял на х64 все и у меня сразу все подчеркнуло.
В чем может быть проблема?

Миниатюры

Visual studio 2010 и SFML 2.1, ошибка LNK1112
 



0



0 / 0 / 1

Регистрация: 15.10.2015

Сообщений: 69

15.01.2017, 20:59

11

Проблему решил. Если комуто будет нужно, просто в настройках, где прописывали пути, тоже поменял на х64.



0



Topic: MSVC++ 2010 fatal error LNK1112: module machine type ‘x64’ conflicts with target  (Read 22291 times)

0 Members and 1 Guest are viewing this topic.

Hello. I’m trying to install SFML 2.0 for Microsoft Visual C++ 2010. Whenever I try to build some sample code to test whether SFML has been installed properly, I get this error:

fatal error LNK1112: module machine type ‘x64’ conflicts with target machine type ‘X86’

 I have looked at many other online resources, but they were either too vague or didn’t work. I guess here is the sample code if you want it.

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), «SFML works!»);
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}

I am running Wndows 7 Professional, 64-Bit

Thanks for reading this  :D If you need more info to debug let me know.


Logged


Not sure where you searched, but the error is quite clear: You’re trying to link x64 libraries with your x86 compiler, which just doesn’t work.
Which SFML package did you download? Did you make sure to switch the compiler of VS to x64?


Logged



I am very new to MSVC++, so I do not know how to change my compiler to x64. Could you show me or link me? Thanks


Logged



Logged


I can’t find the Build menu… am I an idiot? Where is it located?


Logged


I don’t see any mention of the Build menu on that page so I’m not sure it matters.

Also, are you using Express?  If you are and you can’t compile for x64 anyway then you should just go download the x86 binaries instead.  Most x86 programs run fine on x64 so it’s not that important.


Logged


Well, I switched my target machine to x86 and downloaded and set up the 32-bit version of SFML 2.0. Now, it gives me this error.

1>—— Build started: Project: SFML, Configuration: Debug Win32 ——
1>main.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: void __thiscall sf::Window::display(void)» (__imp_?display@Window@sf@@QAEXXZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: void __thiscall sf::Window::close(void)» (__imp_?close@Window@sf@@QAEXXZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: bool __thiscall sf::Window::pollEvent(class sf::Event &)» (__imp_?pollEvent@Window@sf@@QAE_NAAVEvent@2@@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: bool __thiscall sf::Window::isOpen(void)const « (__imp_?isOpen@Window@sf@@QBE_NXZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __thiscall sf::String::~String(void)» (__imp_??1String@sf@@QAE@XZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __thiscall sf::VideoMode::VideoMode(unsigned int,unsigned int,unsigned int)» (__imp_??0VideoMode@sf@@QAE@III@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __thiscall sf::String::String(char const *,class std::locale const &)» (__imp_??0String@sf@@QAE@PBDABVlocale@std@@@Z) referenced in function _main
1>C:UsersCamerondocumentsvisual studio 2010ProjectsSFMLDebugSFML.exe : fatal error LNK1120: 7 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 uptodate, 0 skipped ==========
 

I think I’m making progress. Anyone have any solutions?


Logged


Did you read the official tutorial? If not, you really should!

The error above means that you’re not linking against the needed libraries (Window & System).


Logged


Yes, that was my first step. I did skip the C/c++ -> Preprocessor stuff, as I thought that was optional.


Logged


Don’t «think,» read the tutorial carefully.  The preprocessor part is mandatory for static linking and doesn’t apply to dynamic linking.


Logged


I followed the Preprocessor, and it didn’t change anything. And the error was my fault partially. I had only put sfml-graphics.lib in the Additional Dependencies. (I think that was my problem.) Now when I put in sfml-window-s-d.lib sfml-system-s-d.lib sfml-network-s-d.lib sfml-audio-s-d.lib, it gives me this error:

fatal error LNK1104: cannot open file ‘sfml-window-s-d.lib sfml-system-s-d.lib sfml-network-s-d.lib sfml-audio-s-d.lib’

I’m very confused at this point  :-


Logged


«cannot open file» = File doesn’t exist

Make sure you point to the right directory where the files are actually placed.


Logged


I very much doubt that. I forgot to mention it in the last post, but when I just have sfml-graphics.lib for example, it gives me the earlier error. I think that it is looking for a file named sfml-graphics-s-d.lib sfml-system-s-d.lib etc. instead of looking for multiple files. Is there a way I should separate each one?


Logged


You’re actually completely right.  You have to use ; instead of spaces to separate the filenames.


Logged


12 ответов

Ошибка явная, вы пытаетесь связать библиотеки, которые были скомпилированы с разными целями ЦП. Исполняемое изображение может содержать только чистый x86 (32-разрядный) или чистый x64 (64-разрядный) код. Смешивание невозможно.

Вы изменяете целевой ЦП, создавая новую конфигурацию для проекта, но изменить настройку компоновщика недостаточно. Build + Configuration Manager, активная платформа платформы решений в правом верхнем углу, выберите «Создать» и выберите «x64». Это создает новую конфигурацию с несколькими измененными настройками проекта, что наиболее важно для компилятора, который будет использоваться.

Остерегайтесь того, что до VS2010 64-разрядные компиляторы по умолчанию не установлены. Если вы не видите x64 в комбо-платформе, вам необходимо повторно запустить setup.exe и включить параметр для установки 64-разрядных компиляторов. Затем снова запустите любой установщик пакета обновления, который вы, возможно, применили.

Возможный подход с меньшими болевыми точками — использовать 32-битную версию библиотеки.

Hans Passant
17 май 2010, в 16:08

Поделиться

Я столкнулся с этим и нашел решение.

Сначала о том, как я попал в эту проблему. У меня есть проект, который строит в x86. Затем я использую Configuration Manager для добавления x64, и я ударил эту проблему.

Внимательно изучая BuildLog.htm, я вижу, что оба из них перечислены как параметры компоновщика:
/MACHINE: X64
/машина: X86

Я не могу найти нигде в диалоговом окне «Страницы свойств», где я могу изменить это, поэтому я открываю файл .vcproj и просматриваю соответствующую строку и меняю ее на:   AdditionalOptions = «/STACK: 10000000/машина: x64/debug»

и он работает.

l00g33k
18 нояб. 2011, в 22:12

Поделиться

Перейдите к свойствам проекта → свойства конфигурации → Библиотекарь
Установите целевую машину на MachineX64 (/MACHINE: X64)

Joseph
19 янв. 2014, в 16:11

Поделиться

Поскольку проблема связана с различием в спецификации компиляции и целевой машины (x86 и x64) Выполните следующие шаги:

  • Откройте проект С++, который вы хотите настроить.
  • Выберите кнопку Configuration Manager, чтобы открыть диалоговое окно Configuration Manager.
  • В раскрывающемся списке «Платформа Active Solution» выберите параметр, чтобы открыть диалоговое окно «Новая платформа решений».
  • В раскрывающемся списке Тип или выберите новую платформу выберите 64-битную платформу.

Это решило мою проблему.

hab
13 май 2014, в 22:25

Поделиться

Попробуйте изменить каждое вхождение. Release в.x64Release в свойствах x64. По крайней мере, это сработало для меня…

Thomas
23 дек. 2010, в 04:20

Поделиться

Эта проблема не имеет ничего общего с компоновщиком, поэтому изменение ее настройки не повлияет на результат. Вы получаете это, потому что я предполагаю, что вы пытаетесь настроить таргетинг на x86, но по той или иной причине wxcode_msw28d_freechart.lib строится как x64 файл.

Попробуйте найти wxcode_msw28d_freechart.lib и любой исходный код, из которого он получен. Ваша проблема здесь. Посмотрите, есть ли какие-то специальные шаги сборки, которые используют неправильный набор инструментов (x64 вместо x86).

user7484190
29 янв. 2017, в 08:41

Поделиться

Недавно я столкнулся с этой проблемой. Это потому, что я использовал qt (x64) в vs win32. Если вы хотите использовать qt-приложение x64, вы можете выбрать vs x64 — как указано выше. Если вы хотите использовать win32, и, возможно, нет, вам нужно загрузить qt (32bit), а затем правильно настроить среду, например каталог lib и т.д. (Примечание: возможно, вы устарели установить в x64(other version), если вы конвертируете ваш win32 или x64 в другой, Additional Dependencies включает старый каталог!)

Crawl.W
19 авг. 2016, в 01:10

Поделиться

Спасибо за ответы ребятам. Моя проблема заключалась в том, что я изменил решение x64 в Visual Studio до 32 бит в Configuration Manager. В итоге я просто создал новое решение как 32 бит, а затем скопировал свой код на С++, и эта ошибка исчезла. Я думаю, что l00g33k и предложения RogerAttrill, возможно, были решением, но моя работа тоже.

JoeC
08 июль 2015, в 23:08

Поделиться

перед тем, как перейти к шагу «compile -DIPLIB = NONE filename.cxx»
перейдите по пути установки VIsual Studio до командного файла vcvarsall и измените конфигурацию, как показано ниже.

* C:appsMVS9VCvcvarsall.bat x86_amd64 *

теперь следующим шагом должно быть

compile -64bit -DIPLIB = none filename.cxx

это решило проблему для меня

pratap
04 апр. 2013, в 09:22

Поделиться

Обновление для ответов i00g и Thomas, на этот раз для VS2012 (некоторые имена изменены). После копирования настроек x86 в целевую группу x64 с помощью диспетчера конфигурации у вас возникнет проблема по той же причине, что и в предыдущем случае (цели lib не соответствуют настройке x64). Откройте ваш .vcxproj(текстовый редактор) и замените MachineX86 на MachineX64, где это необходимо. (Я все еще не нашел, где это находится на листах свойств….) Это только кажется необходимым для статических libs.

Josh
30 авг. 2012, в 04:14

Поделиться

Я знаю, что это немного устарело, но я подумал, что дам еще один совет.
В моей ситуации я унаследовал это приложение, которое мне пришлось поддерживать.
Проект VS2008 поставляется с той же строкой в ​​C/С++ → OutputFIles → «ObjectFIleName» и «Program Database File Name» (для обеих платформ Win32 и x64).
Поэтому, когда я построил платформу Win32, она построена отлично, но когда я попытался создать x64, я получил ошибку:

Debug64Objectscommon.obj: фатальная ошибка LNK1112: тип модуля модуля «X86» конфликтует с типом целевой машины «x64»

Очевидно, что оба patforms сохраняли common.obj в одном месте, поэтому, когда я пытался создать x64, компоновщик взял существующий файл объекта, который был x86.

Чтобы исправить, я просто заменил существующую строку макросом «$ (IntDir) » для x64 (без кавычек) и удостоверился, что макрос решил правильный путь, как и в остальных проектах.
Это решило мою проблему.

falconK
25 май 2012, в 00:10

Поделиться

Ещё вопросы

  • 0Переменные MySQL и нотации подзапроса
  • 1Как отобразить арабские данные в FPDF?
  • 0PHP-функция почты Outlook UTF8
  • 0Сохранение части строки в другой строке с сохранением исходной строки. C ++
  • 0Есть ли какой-нибудь JQuery, который поможет встроить электронную таблицу Excel для веб-страницы?
  • 1Как программно получить идентификатор рейса DroneDeploy для плана?
  • 1Android: высвобождение ресурсов в onDestroy (); метод
  • 1Gulp: Uglifying Bootstrap 4 js-файлов
  • 1Почему этот Android FileOutputStream генерирует исключение NullPointerException?
  • 0Как отсортировать вектор <pair <int, pair <int, pair <string, pair <int, int>>>>>?
  • 0Включение содержимого страницы PHP в другой
  • 1Обратное генерирование изображения RGB PCA не работает
  • 0Рассчитать сумму каждой строки с помощью jQuery при изменении значения в текстовом поле
  • 1Нестандартное использование уведомления об ожидании в параллельных программах Java
  • 1почему модуль re python2 не может идентифицировать символ u’® ‘
  • 0Проблема получения данных JSON в JavaScript
  • 1Объединение / Пересечение двух наборов без изменения одного из наборов
  • 1Законные варианты использования для UpgradeableReadLock
  • 0Автозаполнение jQuery UI плагин с JSP и сервлетов не работает
  • 1Вызовите родительский метод из экземпляра
  • 1Может ли скала код, скомпилированный с JDK 7, работать на JVM 8?
  • 0Jquery Jplayer не вызывает функцию setMedia при первом вызове функции на моей странице
  • 1AppleScript с Javascript -> получить строку из HREF
  • 1PyCharm не находит зависимости Python при использовании интерпретатора Docker
  • 1Проверка данных формы с помощью Javascript
  • 0Php создать объект в конструкторе
  • 1Сколько места занимает TextView
  • 1Maven-Shade-плагин: сделать банку, а мы на войне Проект?
  • 0php jquery отправляет параметры сообщения на другую страницу php
  • 0bower.json и package.json интерполяция
  • 0Получить данные с URL-адреса для размещения на сайте
  • 1Ошибка пользовательского действия Wix в .NET3.5
  • 0Magento — способ доставки carrier.php
  • 1Добавление диаграммы радара, программирование на Android
  • 1Сортировать строки даты на карте [дубликаты]
  • 0Angular — вернуть разницу в неработающих объектах
  • 1Regex, который обрабатывает строки в кавычках и двойные кавычки для дюймов
  • 0простой скрипт Jquery не работает: /
  • 0Я написал триггер. Но я получил ошибку при использовании оператора case
  • 0При использовании DOM в цикле: Uncaught TypeError: Невозможно прочитать свойство ‘флажок’ с нулевой ошибкой
  • 02 колонка отсутствует содержание
  • 1Создание ярлыка на андроид
  • 0Как получить данные на основе этого критерия?
  • 0применять класс CSS условно, если существует другой класс jquery / rails
  • 1Как использовать System.Windows.Controls.WebBrowser без его отображения?
  • 0как автоматически сфокусироваться на ячейке времени
  • 0JQuery не удается обновить цвет фона CSS
  • 1Asterisk-Java SIP-шоу сверстников
  • 1Загрузка сборки из встроенных ресурсов во время выполнения внутри Библиотечного проекта
  • 0JQuery не может заставить работать

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

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

  • Fatal error lnk1104 не удается открыть файл vcompd lib
  • Fatal error lnk1104 не удается открыть файл msvcrtd lib
  • Fatal error lnk1104 не удается открыть файл kernel32 lib
  • Fatal error lnk1104 не удается открыть файл glut32 lib
  • Fatal error lnk1104 не удается открыть файл dll

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

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