Im not sure I get what your problem is, it seems to work fine for me. However, you should be aware that the output from g++ is most likely going to go to SDTERR and not STDOUT. You can capture that too using this:
FILE *p = popen("g++ main.cpp -o main 2>&1", "r");