Visual studio ошибка 1168

Suddenly, my Visual Studio Express 2010 C++ stopped rebuilding my project.
When I first hit F7 the project builds and runs fine (heck, it’s a hello world example).

Then I make some changes and hit F7 again, then I get:

1>LINK : fatal error LNK1168: cannot open C:UsersusernameDocumentsVisual Studio 2010ProjectsconsoleDebugconsole.exe for writing**<br><br>

Now the funny thing comes:

  1. The app is not running and it’s not shown in the Task Manager.
  2. Going into the project directory and trying to remove it with hands comes with success but the file APPEARS AGAIN FROM NOWHERE.
  3. The system restore is disabled.
  4. I also tried to take the ownership of the whole damn drive.
  5. Every time I delete the file it recreates itself again but sometimes it stops doing that.
  6. If I delete the file (and it recreates after that), and then I start sysinternals procmon then the file disappears.
  7. If I start procmon before — then the file keeps appearing after delete like always.

OS: W7 SP1 64-bit, with latest updates

Any ideas, please?

Amal K's user avatar

Amal K

4,2692 gold badges19 silver badges44 bronze badges

asked Aug 25, 2012 at 17:25

gogiii's user avatar

1

The problem is probably that you forgot to close the program and that you instead have the program running in the background.

Find the console window where the exe file program is running, and close it by clicking the X in the upper right corner. Then try to recompile the program. In my case this solved the problem.

I know this posting is old, but I am answering for the other people like me who find this through the search engines.

answered Jul 6, 2013 at 6:53

CodeMed's user avatar

CodeMedCodeMed

9,40569 gold badges209 silver badges361 bronze badges

7

I’ve encountered this problem when the build is abruptly closed before it is loaded. No process would show up in the Task Manager, but if you navigate to the executable generated in the project folder and try to delete it, Windows claims that the application is in use. (If not, just delete the file and rebuild, which generates a new executable)
In Windows(Visual Studio 2019), the file is located in this directory by default:

%USERPROFILE%sourcereposProjectFolderNameDebug

To end the allegedly running process, open the command prompt and type in the following command:

taskkill /F /IM ApplicationName.exe

This forces any running instance to be terminated.
Rebuild and execute!

answered Sep 17, 2019 at 16:20

Amal K's user avatar

Amal KAmal K

4,2692 gold badges19 silver badges44 bronze badges

1

Restarting Visual Studio solved the problem for me.

answered Jan 7, 2017 at 18:15

Aleksei Mialkin's user avatar

Aleksei MialkinAleksei Mialkin

2,2371 gold badge27 silver badges25 bronze badges

1

In my case, cleaning and rebuilding the project resolved the problem.

Uli Köhler's user avatar

Uli Köhler

12.9k16 gold badges69 silver badges120 bronze badges

answered Mar 2, 2014 at 15:35

Hau Le's user avatar

Hau LeHau Le

1211 silver badge5 bronze badges

If the above solutions didn’t work, you can try this which worked for me.

Open an elevated command prompt (cmd -> Run as administrator), then write following command and hit enter:

wmic process where name='YOUR_PROCESS_NAME.exe' delete

If you see a message: Instance deletion successful., then you will be again able to build and run project from VS.

e.g. in OP’s case, the command will be:

wmic process where name='console.exe' delete

answered Aug 3, 2021 at 9:06

UkFLSUI's user avatar

UkFLSUIUkFLSUI

5,4716 gold badges32 silver badges47 bronze badges

This solved same problem I also came across very well

  1. Close the app if it is still running on the taskbar,
  2. Open cmd (command prompt) and run the following
taskkill /F /IM ApplicationName.exe
  1. Rebuild your project!! error solved!

cs1349459's user avatar

answered Sep 25, 2022 at 1:11

nios's user avatar

niosnios

911 silver badge7 bronze badges

well, I actually just saved and closed the project and restarted VS Express 2013 in windows 8 and that sorted my problem.

answered Apr 8, 2015 at 17:50

Sparsh Jain's user avatar

2

The Reason is that your previous build is still running in the background.
I solve this problem by following these steps:

  • Open Task Manager
  • Goto Details Tab
  • Find Your Application
  • End Task it by right clicking on it
  • Done!

answered Aug 4, 2020 at 12:48

Back2Lobby's user avatar

Back2LobbyBack2Lobby

5036 silver badges12 bronze badges

This can also be a problem from the improper use of functions like FindNextFile when a FindClose is never executed. The process of the built file is terminated, and the build itself can be deleted, but LNK1168 will prevent a rebuild because of the open handle. This can create a handle leak in Explorer which can be addressed by terminating and restarting Explorer, but in many cases an immediate reboot is necessary.

answered Oct 9, 2015 at 2:44

Laurie Stearn's user avatar

Laurie StearnLaurie Stearn

9611 gold badge12 silver badges33 bronze badges

I know this is an old question but thought I’d share how I resolved the issue.

If you’re using Visual Studio and this error occurs, you can try to attach to process (CTRL+ALT+P) and find the «(program).exe» process. When you try to attach to it, an error will display stating that it failed to attach which removes the process from «running» (even though it’s not…) You’ll also be able to delete the (program).exe from your Debug folder.

Hope this helps someone! :)

answered Oct 4, 2019 at 5:25

tw1tch01's user avatar

tw1tch01tw1tch01

491 silver badge4 bronze badges

FINALLY THE BEST WAY WORKED PERFECTLY FOR ME

None of the solutions in this page worked for me EXCEPT THE FOLLOWING

Below the comment sections of the second answer, try the following :

Adding to my above comment, Task Manager does not display the
filename.exe process but Resource Monitor does, so I’m able to
kill it from there which solves the issue without having to reboot.
A__ Jun 19 ’19 at 21:23

answered Aug 14, 2020 at 14:32

Sam's user avatar

SamSam

3693 silver badges11 bronze badges

If none of the above suggested work for you, which was the case for me, just change the project name. It creates a new exe in the new project name. Later when you restart, you can change it back to your original project name.

answered Aug 22, 2021 at 9:43

Rathnavel's user avatar

RathnavelRathnavel

751 silver badge14 bronze badges

I know this is an old thread but I was stumbling in the same problem also. Finding it in task manager is tricky, and I started to grow tired of having to restart my PC every time this happened.

A solution would be to download Process Explorer and there you can search for running tasks. In my case I was having the following error:

1>LINK : fatal error LNK1168: cannot open C:OutBuildVS12_appDebugplatform_test.exe for writing [C:BuildVS12_appplatform_test.vcxproj]

I searched for C:OutBuildVS12_appDebugplatform_test.exe in Process Explorer, killed it and I was able to compile.

answered Sep 15, 2022 at 11:15

Ra'w's user avatar

Ra’wRa’w

1132 silver badges10 bronze badges

I also had this same issue. My console window was no longer open, but I was able to see my application running by going to processes within task manager. The process name was the name of my application. Once I ended the process I was able to build and compile my code with no issues.

answered Sep 12, 2013 at 23:54

Jason's user avatar

JasonJason

1241 gold badge3 silver badges11 bronze badges

Start your program as an administrator. The program can’t rewrite your files cause your files are in a protected location on your hard drive.

Joonatan's user avatar

answered Jan 6, 2014 at 15:07

chosen's user avatar

0

  • Remove From My Forums
  • Вопрос

  • Подскажите пожалуйста. Пишу исходник в Microsoft Visual C++ 2008 Express Edition. Компилирую — все нормально, работает. вношу какие либо изменения в коде и пытаюсь заново скомпилировать. Выдает вот такую ошибку.

    1>—— Построение начато: проект: 5_stepen’, Конфигурация: Debug Win32 ——
    1>Компиляция…
    1>stepen’.cpp
    1>Компоновка…
    1>LINK : fatal error LNK1168: не удается открыть C:UsersAntonDocumentsVisual Studio 2008Projects5_stepen’Debug5_stepen’.exe для записи
    1>Журнал построения был сохранен в «file://c:UsersAntonDocumentsVisual Studio 2008Projects5_stepen’5_stepen’DebugBuildLog.htm»
    1>5_stepen’ — ошибок 1, предупреждений 0
    ========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

    Для устранения приходится сохранить мой.cpp и закрыть прогу. через 2 минуты отрывать. тогда запускается компиляция. Ни чего не могу поделать.

    • Перемещено

      2 октября 2010 г. 0:53
      MSDN Forums Consolidation (От:Visual Studio — отзывы и пожелания)

Ответы

  • Добрый день.

    Такое происходит, когда Ваш файл 5_stepen.exe не доступен для записи. В ОС WinNT это ситуация возникает, когда файл залочен. Причиной может служить следующее: Вы скомпилировали проект и запустили полученный код. Вносите изменения, компилируете, но запись в файл .exe линковщиком не может быть выполнена, т.к. программа продолжает выполняться, т.е. она продолжает висеть в памяти. Для решения проблемы необходимо просто остановить выполнение Вашей программы 5_stepen.exe.

    • Помечено в качестве ответа
      -An-
      9 мая 2010 г. 19:15

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Linker Tools Error LNK1168

Linker Tools Error LNK1168

11/04/2016

LNK1168

LNK1168

97ead151-fd99-46fe-9a1d-7e84dc0b8cc8

Linker Tools Error LNK1168

cannot open filename for writing

The linker can’t write to filename. The file may be in use and its file handle locked by another process, or you may not have write permission for the file, or for the directory or network share it is located in. This error is often caused by a transient condition—for example, a lock held by an anti-virus program, a file search indexing process, or a delay in releasing a lock held by the Visual Studio build system.

To fix this issue, verify that the filename file handle is not locked, and that you have write permission for the file. If it is an executable, verify that it is not already running.

You can use the Windows SysInternals utilities Handle or Process Explorer to determine which process has a file handle lock on filename. You can also use Process Explorer to release locks on open file handles. For information about how to use these utilities, see the Help files that come with them.

If the file is locked by an anti-virus program, you can fix this issue by excluding your build output directories from automatic scanning by the anti-virus program. Anti-virus scanners are often triggered by the creation of new files in the file system, and they hold locks on the files while the scan proceeds. Consult your anti-virus program documentation for details about how to exclude specific directories from scanning.

If the file is locked by a search indexing service, you can fix this issue by excluding your build output directories from automatic indexing. Consult the documentation for the indexing service for more information. To change the Windows search indexing service, use Indexing Options in the Windows Control Panel. For more information, see Search indexing in Windows 10: FAQ.

If your executable can’t be overwritten by the build process, it may be locked by File Explorer. If the Application Experience service has been disabled, File Explorer may hold on to an executable file handle lock for an extended time. To fix this issue, run services.msc and then open the Properties dialog box for the Application Experience service. Change the Startup type from Disabled to Manual.

The VC++ fatal error LNK1168 is a linking error that occurs when a program is unable to open the .exe file for writing. This error is often encountered during the building or debugging process of a VC++ project and can cause the build process to fail. There can be several reasons why this error might occur, including a locked or in-use .exe file, insufficient permissions, or a problem with the linker. In this article, we will explore some of the methods that can be used to resolve this error.

Method 1: Close the Application

To fix the VC++ fatal error LNK1168: cannot open filename.exe for writing, you can close the application that is currently using the file. Here are the steps to do it:

  1. Open Task Manager by pressing Ctrl+Shift+Esc.
  2. Switch to the Processes tab.
  3. Look for the process with the same name as the .exe file that you are trying to build.
  4. Select the process and click End Task.
  5. Try building the project again.

Here is an example code in C++:

#include <iostream>

int main()
{
    std::cout << "Hello, world!" << std::endl;
    return 0;
}

Assuming that you are trying to build this code and getting the LNK1168 error, you can follow the steps above to close the application that is using the output file. Once the application is closed, you should be able to build the project successfully.

Note that this solution only works if the application that is using the file is not essential to your work. If you need the application to be running, you may need to find another solution, such as changing the output file name or location.

Method 2: Change the Build Output Directory

To fix the VC++ fatal error LNK1168: cannot open filename.exe for writing, you can change the Build Output Directory. Here are the steps:

  1. Open your project in Visual Studio.
  2. Right-click on your project in the Solution Explorer and select «Properties».
  3. In the left-hand menu, select «Configuration Properties» -> «General».
  4. In the «General» tab, find the «Output Directory» field and change it to a directory that you have write access to. For example, you can change it to «$(SolutionDir)bin$(Configuration)».
  5. Click «Apply» and then «OK» to save the changes.

Here is an example code snippet that shows how to change the Build Output Directory using CMake:

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin)

And here is an example code snippet that shows how to change the Build Output Directory using MSBuild:

<PropertyGroup>
  <OutputPath>$(SolutionDir)bin$(Configuration)</OutputPath>
</PropertyGroup>

By changing the Build Output Directory, you should be able to fix the VC++ fatal error LNK1168: cannot open filename.exe for writing.

Method 3: Delete the .exe File

To fix the VC++ fatal error LNK1168: cannot open filename.exe for writing, you can try deleting the .exe file. Here are the steps to do it:

  1. Open the folder where your project is saved.
  2. Look for the .exe file with the same name as your project.
  3. Right-click on the .exe file and select «Delete».
  4. Confirm the deletion by clicking «Yes» on the pop-up window.
  5. Rebuild your project.

Here is an example code in C++:

#include <iostream>

int main() {
  std::cout << "Hello World!";
  return 0;
}

In this example, the name of the project is «HelloWorld». So, the .exe file will be named «HelloWorld.exe». If you encounter the VC++ fatal error LNK1168: cannot open HelloWorld.exe for writing, you can follow the steps above to delete the file and rebuild the project.

Note: Make sure to save your work before deleting any files.

Method 4: Check File and Folder Permissions

If you encounter the error «fatal error LNK1168: cannot open filename.exe for writing» while trying to build your VC++ project, it means that the linker is unable to write the output file because it is already in use or does not have the necessary permissions.

One way to fix this issue is to check the file and folder permissions of the output file and its parent directory. Here’s how to do it:

Step 1: Open the Properties window of the output file

In the Solution Explorer, right-click on the output file (usually with the extension .exe) and select «Properties» from the context menu.

Step 2: Check the Read-only attribute

In the Properties window, go to the «General» tab and check if the «Read-only» attribute is enabled. If it is, uncheck it and click «Apply» to save the changes.

Step 3: Check the Security tab

In the Properties window, go to the «Security» tab and click on the «Edit» button. This will open the Permissions dialog box.

Step 4: Check the permissions

In the Permissions dialog box, make sure that the user account you are using to build the project has the necessary permissions to write to the output file and its parent directory. If not, click on the «Add» button to add the user account and grant it the necessary permissions.

Example code

Here’s an example code that sets the file and folder permissions of the output file and its parent directory:

#include 

int main()
{
    // Set the file and folder permissions of the output file and its parent directory
    const wchar_t* filename = L"C:\Path\To\Output\File.exe";
    const wchar_t* dirname = L"C:\Path\To\Output";

    // Get the security descriptor of the file
    PSECURITY_DESCRIPTOR sd = NULL;
    GetNamedSecurityInfoW(filename, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, NULL, NULL, &sd);

    // Set the security descriptor of the file's parent directory
    SetNamedSecurityInfoW(dirname, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, NULL, sd, NULL);

    // Set the security descriptor of the file
    SetNamedSecurityInfoW(filename, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, NULL, sd, NULL);

    // Free the security descriptor
    LocalFree(sd);

    return 0;
}

This code uses the Windows API functions GetNamedSecurityInfoW and SetNamedSecurityInfoW to get and set the security descriptor of the output file and its parent directory. The SE_FILE_OBJECT parameter specifies that the object is a file, and the DACL_SECURITY_INFORMATION parameter specifies that the discretionary access control list (DACL) of the security descriptor is being set or retrieved.

Note that this code should be run with administrative privileges to have the necessary permissions to modify the file and folder permissions.

That’s it! By checking the file and folder permissions of the output file and its parent directory, you should be able to fix the «fatal error LNK1168: cannot open filename.exe for writing» error in your VC++ project.

Method 5: Reinstall Visual Studio

If you are facing the error «LNK1168: cannot open filename.exe for writing» in Visual Studio, one possible solution is to reinstall Visual Studio. Here are the steps to do so:

  1. Uninstall Visual Studio: Go to Control Panel > Programs and Features, select Visual Studio, and click Uninstall.

  2. Download the latest version of Visual Studio: Go to the Visual Studio website and download the latest version of Visual Studio.

  3. Install Visual Studio: Run the Visual Studio installer and follow the instructions to install Visual Studio.

  4. Create a new project: Open Visual Studio and create a new project.

  5. Build the project: Build the project by clicking Build > Build Solution.

  6. Run the project: Run the project by clicking Debug > Start Debugging.

Here is an example code to create a simple «Hello World» application:

#include 
using namespace std;

int main() {
    cout << "Hello World!" << endl;
    return 0;
}

This code will output «Hello World!» to the console when run.

That’s it! Reinstalling Visual Studio should fix the «LNK1168: cannot open filename.exe for writing» error.

I’m trying to compile C++ code (the lines of code itself aren’t relevant because the error is still applicable to even the basic «Hello world» program), and MS Visual Studio continually gives me the «LNK1168» error to do with that the linker can’t write to any filename, and therefore stops me from compiling and testing my code. Nothing appears to be running other than the MVS application itself from what I can see on Task Manager. How can i change it so that I can write to the filename? Im using the latest windows 10 as of 10/24/2015 , as well as MSV2015, and the other ‘LNK1168 Error’ posts on stackoverflow seem to be outdated, any help is appreciated. Thanks.

asked Oct 24, 2015 at 22:45

Bpcameron's user avatar

5

Load 7 more related questions

Show fewer related questions

Возможно, вам также будет интересно:

  • Visual studio не подчеркивает ошибки
  • Visual studio как отключить ошибку
  • Visual studio как включить отображение ошибок
  • Visual studio журнал ошибок
  • Visual studio выдает ошибку не удается запустить программу

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

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