To begin with, you should distinguish between compiling and running.
So I've already compiled my cpp file as follows:
- g++ main.cpp -o main
- ./main
The first step is compiling the source file main.cpp into an executable file named main. The second step is not doing the compilation job, it's actually running the executable main.
Then, to output the running result of a command to a file, you'll do [command] >[filename] (e.g. ./main >test.txt). Essentially this associates the named file with the standard output of the program.
g++ main.cpp > test.txt will write the standard output of running g++ to test.txt, thus you get nothing. Instead you should do ./main >test.txt.
Programs often output error messages to standard error stream, in order to capture these too, you can do ./main >test.txt 2>&1.