The other answers to this question provide one-off, manual solutions to the problem. However, the root cause of the problem in many cases is that Visual Studio is leaving your previous debug session’s process running, or at least extant in a way that maintains a lock on the executable file. You can set Visual Studio to automatically kill such a process when you stop debugging. This would then typically prevent you from getting this error, as well as needing to take manual steps to rectify it.
To instruct Visual Studio to automatically kill the process when debugging stops, set the following option:
Tools—>Options—>Debugging—>General—>Automatically close the console when debugging stops
On Visual Studio 2022 this is very near the bottom of this list.
Personally, I will run a process under Visual Studio with F5 (Debug) which compiles and links the binary first if necessary.
Then the binary crashes, or hits a breakpoint, or I’m tired of waiting, so I will change the source then hit SHIFT-F5 F5. This is «Debug Stop» followed by «Debug» again. I just do that by reflex.
I’m not sure if this flag’s default value changes periodically between releases of Visual Studio, but I don’t recall ever having to set this option before. I generally create very few projects but work on them many years, so maybe I set this option manually every time then forget about it. But on 2022, it does need to be set. I’ve set it and now can work as I recall working in the past.
The other answers to this question provide one-off, manual solutions to the problem. However, the root cause of the problem in many cases is that Visual Studio is leaving your previous debug session’s process running, or at least extant in a way that maintains a lock on the executable file. You can set Visual Studio to automatically kill such a process when you stop debugging. This would then typically prevent you from getting this error, as well as needing to take manual steps to rectify it.
To instruct Visual Studio to automatically kill the process when debugging stops, set the following option:
Tools—>Options—>Debugging—>General—>Automatically close the console when debugging stops
On Visual Studio 2022 this is very near the bottom of this list.
Personally, I will run a process under Visual Studio with F5 (Debug) which compiles and links the binary first if necessary.
Then the binary crashes, or hits a breakpoint, or I’m tired of waiting, so I will change the source then hit SHIFT-F5 F5. This is «Debug Stop» followed by «Debug» again. I just do that by reflex.
I’m not sure if this flag’s default value changes periodically between releases of Visual Studio, but I don’t recall ever having to set this option before. I generally create very few projects but work on them many years, so maybe I set this option manually every time then forget about it. But on 2022, it does need to be set. I’ve set it and now can work as I recall working in the past.
- 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:\Users\Anton\Documents\Visual Studio 2008\Projects\5_stepen’\Debug\5_stepen’.exe для записи
1>Журнал построения был сохранен в «file://c:\Users\Anton\Documents\Visual Studio 2008\Projects\5_stepen’\5_stepen’\Debug\BuildLog.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
-
Помечено в качестве ответа
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:
- Open Task Manager by pressing Ctrl+Shift+Esc.
- Switch to the Processes tab.
- Look for the process with the same name as the .exe file that you are trying to build.
- Select the process and click End Task.
- 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:
- Open your project in Visual Studio.
- Right-click on your project in the Solution Explorer and select «Properties».
- In the left-hand menu, select «Configuration Properties» -> «General».
- 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)».
- 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:
- Open the folder where your project is saved.
- Look for the .exe file with the same name as your project.
- Right-click on the .exe file and select «Delete».
- Confirm the deletion by clicking «Yes» on the pop-up window.
- 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:
-
Uninstall Visual Studio: Go to Control Panel > Programs and Features, select Visual Studio, and click Uninstall.
-
Download the latest version of Visual Studio: Go to the Visual Studio website and download the latest version of Visual Studio.
-
Install Visual Studio: Run the Visual Studio installer and follow the instructions to install Visual Studio.
-
Create a new project: Open Visual Studio and create a new project.
-
Build the project: Build the project by clicking Build > Build Solution.
-
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.
[ +85 ms] executing: [C:\flutter/] git -c log.showSignature=false log -n 1 --pretty=format:%H
[ +93 ms] Exit code 0 from: git -c log.showSignature=false log -n 1 --pretty=format:%H
[ ] b7d4806243a4e906bf061f79a0e314ba28111aa6
[ ] executing: [C:\flutter/] git tag --points-at b7d4806243a4e906bf061f79a0e314ba28111aa6
[ +46 ms] Exit code 0 from: git tag --points-at b7d4806243a4e906bf061f79a0e314ba28111aa6
[ ] 1.27.0-8.0.pre
[ +46 ms] executing: [C:\flutter/] git rev-parse --abbrev-ref --symbolic @{u}
[ +36 ms] Exit code 0 from: git rev-parse --abbrev-ref --symbolic @{u}
[ ] origin/dev
[ ] executing: [C:\flutter/] git ls-remote --get-url origin
[ +33 ms] Exit code 0 from: git ls-remote --get-url origin
[ ] https://github.com/flutter/flutter.git
[ +76 ms] executing: [C:\flutter/] git rev-parse --abbrev-ref HEAD
[ +36 ms] Exit code 0 from: git rev-parse --abbrev-ref HEAD
[ ] dev
[ +161 ms] Artifact Instance of 'AndroidGenSnapshotArtifacts' is not required, skipping update.
[ +1 ms] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[ ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[ ] Artifact Instance of 'FlutterWebSdk' is not required, skipping update.
[ +3 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required, skipping update.
[ ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[ ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[ ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[ ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[ ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[ +1 ms] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[ +67 ms] executing: C:\android\sdk\platform-tools\adb.exe devices -l
[ +57 ms] List of devices attached
[ +12 ms] Artifact Instance of 'AndroidGenSnapshotArtifacts' is not required, skipping update.
[ +28 ms] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[ +25 ms] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[ +25 ms] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[ +28 ms] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[ +2 ms] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[ ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[ +1 ms] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[ ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[ +111 ms] Multiple devices found:
[ +8 ms] Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.19042.804]
[ +17 ms] Edge (web) • edge • web-javascript • Microsoft Edge 88.0.705.81
[ +5 ms] [1]: Windows (windows)
[ +2 ms] [2]: Edge (edge)
[ +2 ms] Please choose one (To quit, press "q/Q")
[ ] :
flutter analyze
Analyzing warehouse...
info - The value of the field '_headers' isn't used - lib\controllers\default\default_controller.dart:5:7 - unused_field
warning - The parameter 'createdAt' is required - lib\controllers\home\branch\branch_controller.dart:8:30 - missing_required_param
warning - The parameter 'id' is required - lib\controllers\home\branch\branch_controller.dart:8:30 - missing_required_param
warning - The parameter 'name' is required - lib\controllers\home\branch\branch_controller.dart:8:30 - missing_required_param
warning - The parameter 'orders' is required - lib\controllers\home\branch\branch_controller.dart:8:30 - missing_required_param
warning - The parameter 'points' is required - lib\controllers\home\branch\branch_controller.dart:8:30 - missing_required_param
warning - The parameter 'updatedAt' is required - lib\controllers\home\branch\branch_controller.dart:8:30 - missing_required_param
7 issues found. (ran in 2.6s)
[√] Flutter (Channel dev, 1.27.0-8.0.pre, on Microsoft Windows [Version 10.0.19042.804], locale en-US)
• Flutter version 1.27.0-8.0.pre at C:\flutter
• Framework revision b7d4806243 (12 days ago), 2021-02-19 09:22:45 -0800
• Engine revision 6993cb229b
• Dart version 2.13.0 (build 2.13.0-30.0.dev)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
• Android SDK at C:\android\sdk
• Platform android-30, build-tools 30.0.3
• ANDROID_HOME = C:\android\sdk
• Java binary at: C:\android studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
• All Android licenses accepted.
[X] Chrome - develop for the web (Cannot find Chrome executable at .\Google\Chrome\Application\chrome.exe)
! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.
[√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.8.6)
• Visual Studio at C:\Program Files (x86)\Microsoft Visual Studio\2019\Community
• Visual Studio Community 2019 version 16.8.31019.35
• Windows 10 SDK version 10.0.18362.0
[√] Android Studio (version 4.1.0)
• Android Studio at C:\android studio
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
[√] VS Code, 64-bit edition (version 1.53.2)
• VS Code at C:\Program Files\Microsoft VS Code
• Flutter extension version 3.20.0
[√] Connected device (2 available)
• Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.19042.804]
• Edge (web) • edge • web-javascript • Microsoft Edge 88.0.705.81
! Doctor found issues in 1 category.