Anyone know how to solve the error of “collect2.exe: error: ld returned 1 exit status” when a program in C is running?

Overall, your problem is that you’re trying to run a program that is interactive from within Sublime; it doesn’t support that. Sublime captures output your program sends to stdout and stderr and displays it in the output panel, but it does’t connect the panel to stdin.

So, the scenario you’re encountering works like this:

  1. You run your program, which is interactive (in your case it prompts for input via scanf(), and it launches and prompts you for input
  2. You try to enter input, but nothing happens because stdin isn’t connected.
  3. You try to run your program again (or modify it and build it again thinking you might have an issue).
  4. The version you previously tried to run is still running in the background waiting for input you can’t provide, and windows locks executable files while the program is running. So, when the linker (collect2) tries to link the executable during the build, it can’t because the file is locked, hence the permission error.

You can clear the error by killing the program running in the background, which you can do via the Tools > Cancel Build if you do it before this error occurs; if you’ve already seen the error this likely won’t work because this only cancels the most recent build, which would be the one where the error occurred.

The other thing you can do is use something external to kill it; the task manager on windows, kill from a terminal on Linux/OSX, etc. You’ll need to do it this way if you’re already seeing the error.

Note however that this doesn’t solve your underlying problem because you’re still trying to run an interactive program. In order to do that from within Sublime you need to create a custom sublime-build that allows for this. Generally you’d either have it spawn an external terminal and run the program in there, or use a package like Terminus if you want to keep it internal.

In order to set this up, you need to be familiar with the sequence of commands that are needed to compile, link and run a program in one command, which you can get by checking what the build system you’re currently using is (assuming you didn’t create it yourself).

This video on buffering and interactive builds in Sublime (disclaimer, I’m the author) has information and examples of how Terminus can be used for something like this if you’d like more information.

Leave a Comment