Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling C++-code without a file

I'm trying to compile some C++ code using your standard g++ compiler. However, rather than compiling from a file:

main.cpp:

#include <iostream>

int main(){
    std::cout << "Hello World!\n";
    return 0;
}

I would prefer to do something like

g++ ... "#include <iostream>\n int main(){ std::cout << \"Hello World!\n\"; return 0;}"

A previous post from stackoverflow showed that

echo "int main(){}" | gcc -Wall -o testbinary -xc++ -

works but I would like to know how it works and better yet, if there is a way to do this without the need to pipe the contents.

EDIT:

I'm doing run-time code generation where I need to generate a shared library and load the functions created.

I thought there would be a flag to tell the compiler "hey, I'm giving you the source code and not the file".

Thanks again for the help!

like image 950
Yuuta Avatar asked Jul 17 '13 14:07

Yuuta


2 Answers

echo "int main(){}" | gcc -Wall -o testbinary -xc++ -

works but I would like to know how it works and better yet, if there is a way to do this without the need to pipe the contents.

Alternatively you can say (e.g. in a shell-script):

gcc -Wall -o testbinary -xc++ - << EOF
int main(){}
EOF
like image 92
πάντα ῥεῖ Avatar answered Sep 19 '22 12:09

πάντα ῥεῖ


The compiler reads from an input source - either the stdin or a file supplied. You need a pipe to supply something from elsewhere to the compiler. There is no other choice (and of course, some compilers may not have an option to read from stdin either)

like image 25
Mats Petersson Avatar answered Sep 20 '22 12:09

Mats Petersson