Search code examples
c++environment-variablesvscode-debugger

Compiled C++ code produces no terminal output, but VSCode debugger does. Using a -static flag fixes this, but is not a viable solution


I want to print all palindromic numbers that are the product of two three-digit numbers.

#include <iostream>

int main() {

    for (int i = 999; i > 100; i--) {
        std::cout << "Checking numbers for i=" << i << "\n";
        for (int j = 999; j > 100; j--) {
            int k = i * j;
            int temp_k = k;
            int reverse_k = 0;
            int remainder_k;

            while(temp_k != 0) {
            remainder_k = temp_k % 10;
            reverse_k = reverse_k * 10 + remainder_k;
            temp_k /= 10;
            }
            
            if (k == reverse_k) {
                std::cout << k << "\n";
            }
        }
    }
}

When I click Terminal > Run build task, I get an executable and the following output:

Starting build...
C:/msys64/mingw64/bin/g++.exe -fdiagnostics-color=always -g C:\mydirectory\palindromic.cpp -o C:\mydirectory\palindromic.exe

Build finished successfully.
 *  Terminal will be reused by tasks, press any key to close it. 

When I run this executable, a terminal window appears, then closes. There is no output at all (it is not a case of the window closing very quickly due to not closing with std::cin.get(); ).

However, if I click Run > Start Debugging, I get all of the terminal output in VSCode, i.e.

[...]
Checking numbers for i=112
84448
65856
48384
42224
29792
23632
Checking numbers for i=111
[...]

I have tried reinstalling MSYS2 and I have a PATH variable pointing to C:\msys64\mingw64\bin. This has not fixed the issue. Outputs of where for gcc, g++ and gdb:

where g++

C:\msys64\mingw64\bin\g++.exe

where gcc

C:\msys64\mingw64\bin\gcc.exe

where gdb

C:\msys64\mingw64\bin\gdb.exe

If I compile in the VS Code terminal using g++ -Bstatic -static palindrome.cpp and then run a.exe, it works. Statically linking my libraries is not a good fix though.


Solution

  • Using Visual Studio 2019 instead of VS Code allowed me to compile executables that behave as expected. Reinstalling VS Code also allows me to compile executables that behave as expected.