Fatal error lnk1181 cannot open input file libpq lib

I've been encountering a strange bug in Visual Studio 2010 for some time now. I have a solution consisting of a project which compiles to a static library, and another project which is really simp...

I’ve been encountering a strange bug in Visual Studio 2010 for some time now.

I have a solution consisting of a project which compiles to a static library, and another project which is really simple but depends on this library.

Sometimes, in the last days extremely frequent, after Rebuilding the Solution or just compiling it with 1-3 changed source files, I get the following error:

2>LINK : fatal error LNK1181: cannot open input file 'thelibrary.lib'
========== Rebuild All: 1 succeeded, 1 failed, 0 skipped ==========

Where compiling thelibrary.lib was a success without any errors or warnings.

I have tried cleaning the solution, but that doesn’t always work.

  • What is wrong here?

BartoszKP's user avatar

BartoszKP

34.2k14 gold badges104 silver badges129 bronze badges

asked Jun 23, 2011 at 8:33

Komn's user avatar

2

In Linker, general, additional library directories, add the directory to the .dll or .libs you have included in Linker, Input.
It does not work if you put this in VC++ Directories, Library Directories.

answered Jun 25, 2012 at 2:19

Chris Thorne's user avatar

I can see only 1 things happening here:
You did’t set properly dependences to thelibrary.lib in your project meaning that thelibrary.lib is built in the wrong order (Or in the same time if you have more then 1 CPU build configuration, which can also explain randomness of the error). ( You can change the project dependences in: Menu->Project->Project Dependencies )

answered Jun 23, 2011 at 8:51

Sasha's user avatar

SashaSasha

8365 silver badges9 bronze badges

4

Go to:

Project properties -> Linker -> General -> Link Library Dependencies set No.

user's user avatar

user

86.7k18 gold badges198 silver badges190 bronze badges

answered May 29, 2012 at 11:50

EkaYuda's user avatar

EkaYudaEkaYuda

1271 silver badge4 bronze badges

1

I recently hit the same error. Some digging brought up this:
http://support.microsoft.com/kb/815645

Basically, if you have spaces in the path of the .lib, that’s bad. Don’t know if that’s what’s happening for you, but seems reasonably possible.

The fix is either 1) put the lib reference in «quotes», or 2) add the lib’s path to your Library Directories (Configuration Properties >> VC++ Directories).

answered Nov 11, 2011 at 13:05

Clippy's user avatar

ClippyClippy

3543 silver badges10 bronze badges

2

I had the same issue in both VS 2010 and VS 2012.
On my system the first static lib was built and then got immediately deleted when the main project started building.

The problem is the common intermediate folder for several projects. Just assign separate intermediate folder for each project.

Read more on this here

answered Sep 29, 2013 at 10:50

alexkr's user avatar

alexkralexkr

4,5641 gold badge23 silver badges21 bronze badges

1

I solved it with the following:

Go to View-> Property Pages -> Configuration Properties -> Linker -> Input

Under additional dependencies add the thelibrary.lib. Don’t use any quotations.

answered Feb 7, 2013 at 3:08

user2049230's user avatar

I had a similar problem in that I was getting LINK1181 errors on the .OBJ file that was part of the project itself (and there were only 2 .cxx files in the entire project).

Initially I had setup the project to generate an .EXE in Visual Studio, and then in the
Property Pages -> Configuration Properties -> General -> Project Defaults -> Configuration Type, I changed the .EXE to .DLL. Suspecting that somehow Visual Studio 2008 was getting confused, I recreated the entire solution from scratch using .DLL mode right from the start. Problem went away after that. I imagine if you manually picked your way through the .vcproj and other related files you could figure out how to fix things without starting from scratch (but my program consisted of two .cpp files so it was easier to start over).

Vikdor's user avatar

Vikdor

23.8k10 gold badges61 silver badges83 bronze badges

answered Oct 7, 2012 at 4:43

user1726157's user avatar

user1726157user1726157

2512 silver badges4 bronze badges

I’m stumbling into the same issue. For me it seems to be caused by having 2 projects with the same name, one depending on the other.

For example, I have one project named Foo which produces Foo.lib. I then have another project that’s also named Foo which produces Foo.exe and links in Foo.lib.

I watched the file activity w/ Process Monitor. What seems to be happening is Foo(lib) is built first—which is proper because Foo(exe) is marked as depending on Foo(lib). This is all fine and builds successfully, and is placed in the output directory—$(OutDir)$(TargetName)$(TargetExt). Then Foo(exe) is triggered to rebuild. Well, a rebuild is a clean followed by a build. It seems like the ‘clean’ stage of Foo.exe is deleting Foo.lib from the output directory. This also explains why a subsequent ‘build’ works—that doesn’t delete output files.

A bug in VS I guess.

Unfortunately I don’t have a solution to the problem as it involves Rebuild. A workaround is to manually issue Clean, and then Build.

answered Apr 25, 2013 at 5:26

Nick's user avatar

I don’t know why, but changing the Linker->Input->Additional Dependencies reference from «dxguid.lib» to «C:Program Files (x86)Microsoft DirectX SDK (June 2010)Libx86dxguid.lib» (in my case) was the only thing that worked.

answered Dec 3, 2013 at 7:56

Vic's user avatar

VicVic

4586 silver badges14 bronze badges

Maybe you have a hardware problem.

I had the same problem on my old system (AMD 1800 MHz CPU ,1GB RAM ,Windows 7 Ultimate) ,until I changed the 2x 512 MB RAM to 2x 1GB RAM. Haven’t had any problems since. Also other (minor) problems disappeared. Guess those two 512 MB modules didn’t like each other that much ,because 2x 512 MB + 1GB or 1x 512 MB + 2x 1GB didn’t work properly either.

answered Jun 24, 2011 at 8:09

engf-010's user avatar

engf-010engf-010

3,9701 gold badge14 silver badges25 bronze badges

For me the problem was a wrong include directory. I have no idea why this caused the error with the seemingly missing lib as the include directory only contains the header files. And the library directory had the correct path set.

answered Oct 17, 2014 at 12:54

mgttlinger's user avatar

mgttlingermgttlinger

1,4152 gold badges21 silver badges35 bronze badges

You can also fix the spaces-in-path problem by specifying the library path in DOS «8.3» format.

To get the 8.3 form, do (at the command line):

DIR /AD /X

recursively through every level of the directories.

answered Jun 4, 2016 at 22:15

Pierre's user avatar

PierrePierre

3,9642 gold badges33 silver badges39 bronze badges

I had the same problem. Solved it by defining a macro OBJECTS that contains all the linker objects e.g.:

OBJECTS = target.exe kernel32.lib mylib.lib (etc)

And then specifying $(OBJECTS) on the linker’s command line.

I don’t use Visual Studio though, just nmake and a .MAK file

0xdb's user avatar

0xdb

3,4741 gold badge19 silver badges36 bronze badges

answered Nov 4, 2017 at 16:47

Martin van Rijen's user avatar

I had the same error when running lib.exe from cmd on Windows with a long argument list. apparently cmd.exe has max line length of about 8K characters, which resulted that the filenames at the end of this threshold got changed, thus resulting in bad filename error.
my solution was to trim the line. I removed all paths from filenames and added single path using /LIBPATH option. for example:

/LIBPATH:absolute_path /OUT:outfilename filename1.obj filename2.obj ... filenameN.obj

answered Nov 1, 2018 at 14:31

Haim Itzhayek's user avatar

I found a different solution for this…

Actually, I missed comma separator between two library paths. After adding common it worked for me.

Go to: Project properties -> Linker -> General -> Link Library Dependencies
At this path make sure the path of the library is correct.

Previous Code (With Bug — because I forgot to separate two lib paths with comma):

<Link><AdditionalLibraryDirectories>....Buildlib$(Configuration)**....BuildRelease;**%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

Code after fix (Just separate libraries with comma):

<Link><AdditionalLibraryDirectories>....Buildlib$(Configuration)**;....BuildRelease;**%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

Hope this will help you.

Ehsan Mohammadi's user avatar

answered May 8, 2019 at 11:32

Shubham's user avatar

In my case I had the library installed using NuGet package (cpprestsdk) AND I falsely added the lib to the Additional Dependancies in the Linker settings. It turns out, the package does it all for you.

The linker then tried to find the library in the library path and of course could not find it.

After removing the library from the Additional Dependencies everything compiled and linked fine.

answered May 10, 2019 at 11:35

Bojan Hrnkas's user avatar

Bojan HrnkasBojan Hrnkas

1,54816 silver badges22 bronze badges

Not quite the answer to OP’s question as I am using CMake with Visual Studio as a generator but I personally also just encountered the same issue (I am using Visual Studio toolchain, but not the IDE to build stuff).

My fix was target linking the directory of the directory of the libraries (I had a few) before target linking the library.

//Works
target_link_directories(MyExe PRIVATE /out/of/scope/path/to/lib)
foreach(X IN LISTS LIBSLISTNAMES)
    target_link_libraries(MyExe ${X})
endforeach()

//Throws cannot open cannot open input file error
 foreach(X IN LISTS LIBSLISTNAMES)
    target_link_libraries(MyExe /out/of/scope/path/to/lib/${X})
endforeach()

Not sure what is happening under the hood, but maybe VS IDE has equivalent setting somewhere?

answered Jun 17, 2021 at 0:36

Curious_Student's user avatar

I’ve also experienced this problem. For me the dependencies were properly set, but one of the projects in my solution wasn’t selected for building in the configuration (VS 2022 pro).

I eventually figured out thanks to output in Build -> Clean Solution that mentioned one of the project in dependency chain being disabled. Interesingly enough, when trying to build the disabled project it wouldd not properly build its dependencies.

answered Feb 14, 2022 at 15:14

Barnaba's user avatar

BarnabaBarnaba

6475 silver badges19 bronze badges

I created a bin directory at the project_dir level, then created a release/debug directory inside the bin folder, which solved the problem for me.

Matt's user avatar

Matt

73.7k26 gold badges151 silver badges180 bronze badges

answered Aug 19, 2013 at 17:11

Ravi Sohal's user avatar

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

fluxxu opened this issue

Sep 19, 2016

· 6 comments


Closed

Can not link using msvc

#3

fluxxu opened this issue

Sep 19, 2016

· 6 comments

Comments

@fluxxu

Hi,

I tried to install diesel_cli on my Windows 10
It says

note: LINK : fatal error LNK1181: cannot open input file 'pq.lib'

There is a libpq.lib in the pqsql/lib folder, if I rename it to pq.lib, diesel_cli can be installed successfully…
Maybe this is a cargo’s issue?

Thanks.

diesel-rs/diesel#487

This was referenced

Nov 23, 2016

@tyoc213

same here? was trying to use diesel on Win 10… but got this issue.

Also exactly what postgree do I need to install @fluxxu ?

@fluxxu

@tyoc213

For Postgres server, I use Docker because I don’t want Postgres to create user on my computer.
For client library to link with diesel, I used EnterpriseDB zip archive here:
https://www.enterprisedb.com/download-postgresql-binaries
Assume you extract it to X:pgsql
You need to rename or copy X:pgsqlliblibpq.lib to X:pgsqllibpq.lib otherwise cargo can not find it.
Don’t forget to set environment variable PQ_LIB_DIR to X:pgsqllib

Related issue:
diesel-rs/diesel#487

😄

@rlepidi

This still isn’t working for me. I know I have the updated version because it says LNK1181: cannot open input file 'libpq.lib'. I have my PG_LIB_DIR env var set to C:Program FilesPostgreSQL9.4lib and can confirm libpq.lib lives there. Is there something else I can try?

@sgrif

PG_LIB_DIR doesn’t do anything. As per the readme, you need to do on of:

  • have LIB_PQ_DIR is set and pointing to the right directory
  • have pg_config.exe on your PATH
  • have pkg-config on your PATH and configured to be able to find libpq.

@rlepidi

Sorry, that was a typo. I actually have it set as PQ_LIB_DIR. (readme has it wrong, see my PR)

I figured it out. I was trying all these things and just doing a cargo build on my project, which never ran build.rs again since pq-sys already built successfully (it just failed to link). Once I did a cargo clean and it reran build.rs, it picked up my env var and linked successfully.

@ysinsane

I encounted this issue too. Firstly, I get this
LNK1181: cannot open input file 'libpq.lib'
Then I installed postgrel server.(I don’t really understand I need to install a server to get this lib. Why libpq.DLL is not enough.)
Now I get
note: LINK : fatal error LNK1181: cannot open input file 'pq.lib'
So I copy libpq.lib and named it as ‘pq.lib’. Then I run cargo install(I did not run cargo clean) … everything works!

Sivakumar

Sivakumar

Posted on Jul 29, 2020

• Updated on Nov 3, 2020

Hello There!. This is my first ever blog post.

Very recently, I have started exploring Rust language and I already have so much fun learning this language.

I was trying to do some basic database CRUD implementations in Rust and as you know, most famous framework for the same is Diesel .

Since I faced lots of issues while setting up Diesel on my local machine, I thought of putting it as blog post so that, it can be of useful to someone who will face similar issues of mine.

For your information, I am using Windows 10 operating system (64-bit) and Rust v1.45.0.

In case if you have not installed Rust with Visual C++ build tools , when you’re trying to install Diesel framework, you may get some errors related to Linker.exe. It is better to install latest version of Microsoft Visual C++ build tools first and then re-install Rust on your computer.

Installing Diesel framework is a 2-step process.

Step 1: Install Diesel using CARGO

cargo install diesel

Enter fullscreen mode

Exit fullscreen mode

As of writing of this post, Diesel supports MySQL, Postgres and SQLite. The above command expects all the client tools pre-exists on your computer.

If you have one of the client tools, you can use following command

cargo install diesel --no-default-features --features mysql postgres sqlite

Enter fullscreen mode

Exit fullscreen mode

In my case, i am having Postgres so, i tried with

cargo install diesel --no-default-features --features postgres

Enter fullscreen mode

Exit fullscreen mode

Initially, when i try the above command, I was getting following error

error: diesel = note: link : fatal error lnk1181: cannot open input file 'libpq.lib'

Enter fullscreen mode

Exit fullscreen mode

After spending few minutes on google, I figured out, i need to setup environment variable named PQ_LIB_DIR mapped to lib directory of Postgres installation folder.

In my computer, I have Postgres installed on C:Program FilesPostgres12. So, I setup PQ_LIB_DIR as C:Program FilesPostgres12lib.

Due to spaces in the folder name, cargo install diesel threw me error message. So, I had to correct it like c:/Program Files/Postgres/12/lib to solve the first level of issue.

Step 2: Setting up Diesel

To setup Diesel, we need run following command

diesel setup

Enter fullscreen mode

Exit fullscreen mode

It throws me following error:

The code execution cannot proceed because libpq.dll was not found.

Enter fullscreen mode

Exit fullscreen mode

Even though, I had added PQ_LIB_DIR environment variable, I got the above error. After a little search, I found out that, diesel is not able to find the libpq.dll from folders listed under PATH variable. After added PQ_LIB_DIR to PATH variable, that error was gone.

Then, I was getting another error:

The code execution cannot proceed because libssl-1_1-x64.dll was not found.

Enter fullscreen mode

Exit fullscreen mode

This dll file is shipped alongwith postgres and it can be found under BIN folder. After I have added Postgres’ BIN folder to PATH variable, diesel setup was completed successfully.

Hope you find the above post useful. Please share your feedback in case if i miss any other points.

Happy reading!!!

Problem

«LNK1181:cannot open input file…» error when including external libraries

Resolving The Problem

SYMPTOM

When building a Rose RealTime executable, the following error is encountered during the linking phase of the build:

LINK : fatal error LNK1181: cannot open input file "xxx.lib"  (where "xxx" is the external library name).

CAUSE

The aforementioned error occurs when including a library in a Rose RealTime component and the compiler is unable to locate the library.

RESOLUTION

To resolve this problem, ensure that the paths to any external libraries to be included in your Rose RealTime component are defined in the «UserLibraries» field of the C++ Executable tab of the Component Specification. We recommend using virtual path maps to do this.

To define a virtual path map in Rose RealTime:

1. Click File > Edit Path Map to open the Virtual Path Map dialog.
2. Type the name of the new virtual path in the Symbol field (for example, «EXT_LIB»), but omit the leading «$» character.
3. In the Actual Path field, enter the location of the external libraries to be included.
4. Click Add. A new virtual path map symbol, $EXT_LIB, has been defined.

To use a virtual path map to include an external library in a Rose RealTime component:

1. Open the Component Specification and go to the C++ Executable tab.
2. In the UserLibraries field, use the pre-defined virtual path map symbol followed by the library name to add the external library to the component. For example, using the virtual path map defined above, the inclusion statement would look like this: $EXT_LIB/mylib.lib (where «mylib» is the actual library name).
3. Apply the change and Save your model.

For more information on using virtual path maps, please refer to the following section in the Rose RealTime on-line help:

Team Development > Storage of Model Data > Virtual Path Maps

Note: If the UserLibraries text above is required for all components in a project, then a project specific «Property Set» can be created. See Toolset Guide > Customizing the Toolset > Managing Model Properties.

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

RRS feed

  • Remove From My Forums
  • Question

  • I compiled my program after doing all those settings in «Project Setting Menu»
    but i got an error :

    fatal error LNK1181: cannot open input file «,.obj»

    I think there is some problem in the settings. I checked all the settings tht i know but still not able to remove this error.

    If anyone know about the settings in VC++ then plz reply
    any help will be of great use
    Thanks in advance


Answers

  •  belikekhushi wrote:

    I checked my linker settings.. Earlier i was using comma to seperate entries sso in was getting error with «,.obj» input file

    Now, i replaced comma with semi-colon and now i am getting same error with «;.obj» file..

    I think the libraries files have to be separated with a single space. If path contains a space, then use quotation marks.

    Otherwise «;» and «,» are treated as file names with «.obj» default extension.

    Hope it helps.


  • Check you linker settings. Did you placed a comma into one of those fields? Separate entries with a semicolon.

  • Sorry! I have no idea.

    I even can not see that there is a part like this in the command line.

    Try to create a new project from scratch.

All replies

  • Check you linker settings. Did you placed a comma into one of those fields? Separate entries with a semicolon.

  • I checked my linker settings.. Earlier i was using comma to seperate entries sso in was getting error with «,.obj» input file

    Now, i replaced comma with semi-colon and now i am getting same error with «;.obj» file..

    Plz help me out…

  • What did you entered in you linker settings.

  • I tried following two:

    First time i tried this one :

    «E:MSDev98MyProjectsDCMConverterpngDebugpng.lib» ; «E:MSDev98MyProjectsDCMConverterjpegDebugjpeg.lib» ; «E:MSDev98MyProjectsDCMConverterzlibDebugzlib.lib» ; «E:MSDev98MyProjectsDCMConvertertiffDebugtiff.lib» ; «E:MSDev98MyProjectsDCMConvertercximageDebugcximage.lib»

    and second time i tried this one:

    E:MSDev98MyProjectsDCMConverterpngDebugpng.lib ; E:MSDev98MyProjectsDCMConverterjpegDebugjpeg.lib ; E:MSDev98MyProjectsDCMConverterzlibDebugzlib.lib ; E:MSDev98MyProjectsDCMConvertertiffDebugtiff.lib ; E:MSDev98MyProjectsDCMConvertercximageDebugcximage.lib

    In both cases i m getting the same error msg

    Linking…
    LINK : fatal error LNK1104: cannot open file «;.obj»
    Error executing link.exe.

  • Look into the build log, what is the command line for the build process.

  • I am sending you the command line of build log

    I am new to VC++ so, Its difficult for me to find error in this log.

    Build Log

    --------------------Configuration: DCMConverter - Win32 Debug--------------------

    Command Lines

    Creating temporary file "C:DOCUME~1ADMINI~1LOCALS~1TempRSP10B.tmp" with contents [ E:MSDev98MyProjectsDCMConverterpngDebugpng.lib ; E:MSDev98MyProjectsDCMConverterjpegDebugjpeg.lib ; E:MSDev98MyProjectsDCMConverterzlibDebugzlib.lib ; E:MSDev98MyProjectsDCMConvertertiffDebugtiff.lib ; E:MSDev98MyProjectsDCMConvertercximageDebugcximage.lib /nologo /subsystem:windows /incremental:yes /pdb:"Debug/DCMConverter.pdb" /debug /machine:I386 /nodefaultlib:"msvcprtd.lib" /nodefaultlib:"msvcrtd.lib" /nodefaultlib:"msvcrt.lib" /out:"Release/DCMConverter.exe" /pdbtype:sept /libpath:"D:cximage599c_fullCxImageCxImageDLLDebug" /libpath:"D:dcmtkdcmtk-3.5.3Debug" /libpath:"D:dcmtkconfiginclude" /libpath:"D:dcmtkdcmjpeginclude" /libpath:"D:dcmtkofstdinclude" /libpath:"D:dcmtkdcmdatainclude" /libpath:"D:dcmtkdcmimgleinclude" /libpath:"D:dcmtkdcmimageinclude" /libpath:"D:dcmtkdcmjpeglibijg8" /libpath:"D:dcmtkdcmjpeglibijg12" /libpath:"D:dcmtkdcmjpeglibijg16" /libpath:"D:dcmtkzlib-1.2.1" /libpath:"D:dcmtktiff-v3.6.1libtiff" /libpath:"D:dcmtklibpng-1.2.5" .DebugDCMConverter.obj .DebugDCMConverterDlg.obj .DebugStdAfx.obj .DebugxImageDCM.obj .DebugDCMConverter.res ] Creating command line "link.exe @C:DOCUME~1ADMINI~1LOCALS~1TempRSP10B.tmp"

    Output Window

    Linking... LINK : fatal error LNK1104: cannot open file ";.obj" Error executing link.exe.

    Results

    DCMConverter.exe - 1 error(s), 0 warning(s)
  • Sorry! I have no idea.

    I even can not see that there is a part like this in the command line.

    Try to create a new project from scratch.

  • As Martin suggested, try creating project from scratch and see if the issue still reproduces.

    Thanks,
    Ayman Shoukry
    VC++ Team
  • hello

     i’am a new member; please will tell me if you have already found a solution for this problem , because i have the same problem, please it’s very urgent for me :

    the message is:

    Linking…

    LINK : fatal error LNK1181: cannot open input file ‘.DebugAssemblyInfo.obj’

    thanks a lot

  • Please create a new thread.

    Check your linker settings as I wrot ein this thread. Do you have an module named AssemblyInfo?

  • thanks for your answer

    i have a module named AssemblyInfo, but my programm don’t generate AssemblyInfo.obj .

    I don’t know what to change in linker settings will you help me please!

  • What kind of project is this? Managed C++/CLI?

    What did you added to the project, what source files you have?

  • it’s C++, with a dll main. a added sources that i had in visual studio C++ , and now i want to have them in visual studio .Net

    did you think that i should change liker settings ?

  • hello

     i’am a new member; please will tell me if you have already found a solution for this problem , because i have the same problem, please it’s very urgent for me :

    the message is:

    Linking…

    LINK : fatal error LNK1181: cannot open input file ‘.DebugAssemblyInfo.obj’

    thanks a lot

  • Whats in your linker settings?

  •  belikekhushi wrote:

    I checked my linker settings.. Earlier i was using comma to seperate entries sso in was getting error with «,.obj» input file

    Now, i replaced comma with semi-colon and now i am getting same error with «;.obj» file..

    I think the libraries files have to be separated with a single space. If path contains a space, then use quotation marks.

    Otherwise «;» and «,» are treated as file names with «.obj» default extension.

    Hope it helps.


  • hi,

    sorry, if i m late in replying that query.

    i am not very good at vc++ but yes i have two options to go for ur problem:

    first, go to the linker settings give their full path (like D;test……) and not the relative one…

    then build ur code again and then execute…

    if this helps thn its ok otherwise delete this «.DebugAssemblyInfo.obj» entry from the linker settings and then build the whole project again…

    hope one of these may help you…

  • I confirm, after a lot of try i find that the libraries files have to be separated with a single space.

  • Hello ,

    I have the same problem, using Visual studio 2008, but i really don’t understand what are the indications! How can I change the linker settings?

    When i look into the Linker…it has many submodules, like Generate, Input….and in the end: Command line, which has the following:

    /OUT:»C:Documents and SettingssimonaMy DocumentsVisual Studio 2008Projects1Debug1.exe» /INCREMENTAL /NOLOGO /MANIFEST /MANIFESTFILE:»Debug1.exe.intermediate.manifest» /MANIFESTUAC:»level=’asInvoker’ uiAccess=’false'» /DEBUG /PDB:»C:Documents and SettingssimonaMy DocumentsVisual Studio 2008Projects1Debug1.pdb» /SUBSYSTEM:WINDOWS /DYNAMICBASE /NXCOMPAT /MACHINE:X86 /ERRORREPORT:PROMPT kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib

    I just wrote a simple Hello world program. I get this error all the time(also in Visual Studio 2005 and Visual Studio 2008):

    Error    1    fatal error LNK1104: cannot open file ‘.Debugmain.obj’    2    2

    Where main is the simple hello world program, whether it’s C++ or C. I tried reinstalling many times. No luck.

    Help , please??

    Thanks

  • Try resetting all your settings from whithin IDE.
    to do so under tool menu click import and export settings then click reset all.

    give it a try.

    regards

    Adi


    A K

  • I have encounterd the same problem,but I can’t find linker in project settings,instead I find library,how can I solve the problem?

  • I ran into a similar problem on Visual Studio 2017.

    The error was indeed cryptic. I got it to work by realizing that I forgot to include some external cpp files that needed to be compiled and built with my project.

    For those of you who run into the problem and found this thread, check and make sure that you haven’t forgot to include:

    1. External .cpp files
    2. That in your Linker –> Input –> Additional Dependencies settings, there’s no blank library like «.» or «$(INHERIT)»


Я уже некоторое время встречаю странную ошибку в Visual Studio 2010.

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

Иногда, в последние дни очень часто, после восстановления решения или просто компиляции его с 1-3 измененными исходными файлами, я получаю следующую ошибку:

2>LINK : fatal error LNK1181: cannot open input file 'thelibrary.lib'
========== Rebuild All: 1 succeeded, 1 failed, 0 skipped ==========

Где компиляция thelibrary.lib имела успех без каких-либо ошибок или предупреждений.

Я пробовал очистить решение, но это не всегда работает.

  • Что здесь не так?

23 июнь 2011, в 10:42

Поделиться

Источник

14 ответов

В Linker, общие, дополнительные каталоги библиотек, добавьте каталог в DLL или .lib, которые вы включили в Linker, Input.
Это не работает, если вы поместите это в каталоги VС++, каталоги библиотек.

Chris Thorne
25 июнь 2012, в 03:43

Поделиться

Перейдите к:

Project properties -> Linker -> General -> Link Library Dependencies set No.

EkaYuda
29 май 2012, в 13:09

Поделиться

Я вижу только 1 вещи, происходящие здесь:
Вы не установили должным образом зависимости от thelibrary.lib в своем проекте, что означает, что thelibrary.lib построен в неправильном порядке (или в то же время, если у вас более 1 конфигурация сборки CPU, что также может объяснить случайность ошибки), (Вы можете изменить зависимости проекта в: Menu- > Project- > Project Dependencies)

Sasha
23 июнь 2011, в 09:45

Поделиться

Недавно я попал в ту же ошибку. Некоторое копание вызвало это:
http://support.microsoft.com/kb/815645

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

Исправление: либо 1) поместить ссылку на lib в «кавычки», либо 2) добавить путь lib к вашим библиотечным каталогам (Свойства конфигурации → Каталоги VС++).

Clippy
11 нояб. 2011, в 13:35

Поделиться

У меня была такая же проблема как в VS 2010, так и в VS 2012.
В моей системе была создана первая статическая библиотека, а затем сразу же удалена при запуске основного проекта.

Проблема заключается в общей промежуточной папке для нескольких проектов. Просто назначьте отдельную промежуточную папку для каждого проекта.

Подробнее об этом здесь

alexkr
29 сен. 2013, в 12:46

Поделиться

Я решил это со следующим:

Перейдите в View- > Страницы свойств → Свойства конфигурации → Коннектор → Вход

В дополнительных зависимостях добавьте thelibrary.lib. Не используйте никаких цитат.

user2049230
07 фев. 2013, в 04:52

Поделиться

У меня была аналогичная проблема, так как я получал ошибки LINK1181 в файле .OBJ, который был частью самого проекта (и во всем проекте было всего 2 файла .cxx).

Сначала я установил проект для создания .EXE в Visual Studio, а затем в
Property Pages -> Configuration Properties -> General -> Project Defaults -> Configuration Type, я изменил .EXE на .DLL. Подозревая, что Visual Studio 2008 каким-то образом запуталась, я с самого начала воссоздал все решение с нуля с использованием режима .DLL. После этого проблема исчезла. Я предполагаю, что если вы вручную проведете свой путь через .vcproj и другие связанные файлы, вы сможете выяснить, как исправить ситуацию, не начиная с нуля (но моя программа состояла из двух файлов .cpp, поэтому было легче начать все заново).

user1726157
07 окт. 2012, в 05:29

Поделиться

Для меня проблема была неправильной директорией include. Я понятия не имею, почему это вызвало ошибку с, казалось бы, отсутствующей библиотекой lib, поскольку каталог include содержит только заголовочные файлы. И каталог библиотеки имел правильный набор путей.

mgttlinger
17 окт. 2014, в 13:43

Поделиться

Я не знаю почему, но изменив ссылку Linker- > Input- > Additional Dependencies из «dxguid.lib» на «C:Program Files (x86)Microsoft DirectX SDK (июнь 2010)Libx86dxguid.lib» (в моем случае) — единственное, что сработало.

Vic
03 дек. 2013, в 08:06

Поделиться

Я сталкиваюсь с тем же вопросом. Для меня это, по-видимому, вызвано наличием двух проектов с тем же именем, один из которых зависит от другого.

Например, у меня есть один проект с именем Foo, который создает Foo.lib. Затем у меня есть еще один проект, который также называется Foo, который создает Foo.exe и ссылки в Foo.lib.

Я просмотрел файловую активность с Монитором процессов. Похоже, что Foo (lib) создается первым — что является правильным, потому что Foo (exe) помечен как зависящий от Foo (lib). Все это прекрасно и успешно строится и помещается в выходной каталог — $(OutDir) $(TargetName) $(TargetExt). Затем Foo (exe) запускается для восстановления. Ну, перестройка — это чистый, за которым следует сборка. Похоже, что «чистый» этап Foo.exe удаляет Foo.lib из выходного каталога. Это также объясняет, почему работает последующая «сборка», которая не удаляет выходные файлы.

Ошибка в VS, я думаю.

К сожалению, у меня нет решения проблемы, так как она включает Rebuild. Обходной путь заключается в том, чтобы вручную очистить Clean, а затем Build.

Nick
25 апр. 2013, в 06:14

Поделиться

У меня была та же проблема. Решил его, указав макрос OBJECTS, содержащий все объекты компоновщика, например:

OBJECTS = target.exe kernel32.lib mylib.lib (etc)

И затем укажите $(OBJECTS) в командной строке компоновщика.

Я не использую Visual Studio, хотя, просто nmake и .MAK файл

Martin van Rijen
04 нояб. 2017, в 18:39

Поделиться

Вы также можете исправить проблему пробела в пути, указав путь библиотеки в формате DOS «8.3».

Чтобы получить форму 8.3, выполните (в командной строке):

DIR /AD /X

рекурсивно через каждый уровень каталогов.

Pierre
04 июнь 2016, в 23:16

Поделиться

Возможно, у вас есть проблемы с оборудованием.

У меня была такая же проблема на моей старой системе (процессор AMD 1800 МГц, 1 ГБ оперативной памяти, Windows 7 Ultimate), пока я не изменил 2x 512 МБ ОЗУ на 2x 1 ГБ ОЗУ. С тех пор не было никаких проблем. Также исчезли другие (второстепенные) проблемы. Угадайте, что эти два модуля объемом 512 МБ не очень понравились друг другу, потому что 2x 512 МБ + 1 ГБ или 1x 512 МБ + 2x 1 ГБ тоже не работали.

engf-010
24 июнь 2011, в 09:03

Поделиться

Я создал каталог bin на уровне project_dir, а затем создал каталог release/debug внутри папки bin, который решил проблему для меня.

Ravi Sohal
19 авг. 2013, в 17:48

Поделиться

Ещё вопросы

  • 1вызывать одно приложение из другого, Android SDK?
  • 1Макет чата с менеджером BoxLayout
  • 0angularJS проверять ng-repeat поочередно с помощью ng-if
  • 1Проблема перекрытия меток по оси Х Highstock
  • 0Извлечь headerText из JSON в результаты div, основываясь на выборе из выпадающего списка
  • 0Как читать данные из таблицы в MySQL из Java
  • 1Невозможно вызвать getApplicationContext () внутри потока
  • 0SQL-поиск со специальными символами
  • 0Как вызвать всплывающее окно в главной html-странице извне директивы angularjs?
  • 1Попытка разобрать XML с помощью SAX, но ни один из моих тестов JUnit не работает?
  • 0при изменении класса клика
  • 1Как мне написать изображение в xls с нестандартным размером, используя Java и Apache POI
  • 1Как выполнить перенаправление HTTP на стороне сервера вместо мета-обновления
  • 0Попытка вывести самого богатого пользователя в моей базе данных через php
  • 1Почему сетка не следовала за арматурой в режиме редактирования, как получить координаты точек на сетке, размеченной арматурой?
  • 1В Python добавление пустого списка в столбец dataframe с помощью лямбды повышает valueError
  • 1Разделение сеанса Tomcat не работает, когда браузер выполняет вызов на другой сервер
  • 0Не могу получить доступ к запросу пароля из MySQL в Ubuntu
  • 1Эмулятор Azure с полным IIS
  • 1Vuejs — передать слот вложенному ребенку
  • 0Ошибка с оператором соединения
  • 1Как проверить нулевые значения в SqlDataReader, не используя более одного читателя
  • 0Hexdump структуры не выводит правильную информацию
  • 1Объединить и манипулировать двумя столбцами как дата, используя PANDAS
  • 1Ошибка создания бина для org.springframework.beans.propertyeditors.StringTrimmerEditor
  • 0Как объединить все строки с одним и тем же именем в одну таблицу с помощью MYSQL?
  • 0Как использовать Zend Pagination
  • 1Недопустимое имя переменной Statsmodels (Patsy) / объект ‘Series’ не вызывается Ошибка
  • 1Как обеспечить доступ методов действия для конкретного пользователя в контроллере в asp.net mvc
  • 1Как добавить всплывающее окно на рейтинги? [Семантический-интерфейс]
  • 0Как выполнить несколько запросов в sqlapi ++ с оракулом
  • 0Анимация «высота» Jquery на дне
  • 0Невозможно скомпилировать код C ++: неверное преобразование из ‘int’ в ‘node *’
  • 1Apache POI: Word получить размеры изображения
  • 0Фильтр угловых таблиц js не работает для вложенных объектов
  • 0Камера расширения не найдена — PhoneGap 3.0
  • 0Как использовать CONCAT_WS / GROUP_CONCAT в LIKE Mysql?
  • 0Почему IE7 и IE8 будут показывать только содержимое первой вкладки?
  • 1Словарь итерации
  • 0Опция выбора jquery onchange не работает
  • 0Отображать изображения из папки в 5 столбцах
  • 0c ++ вектор push_back с указателем на объект
  • 1получить подстроку между {и}
  • 1Содержимое файла в байтовом массиве?
  • 1Получение текста из списка
  • 0Бэкэнд без состояния безопасен?
  • 1Вложенные списки, Python из bash Output
  • 0Преобразовать текстовую метку в дату
  • 0Вывод цикла из массива garbge после окончания цикла
  • 1Ошибка в соединении с базой данных C # -> OracleDB

Сообщество Overcoder

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

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

  • Fatal error lnk1169 one or more multiply defined symbols found
  • Fatal error lnk1168 не удается открыть exe для записи
  • Fatal error lnk1136 недопустимый или поврежденный файл
  • Fatal error lnk1136 invalid or corrupt file
  • Fatal error lnk1120 неразрешенных внешних элементов

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

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