[Tex/LaTex] Is it possible to insert C++ code into LaTeX

codeprogramming

I mean C++ doing some calculation not inserting the code as a text.

Best Answer

In this solution I use the facilities of fancyvrb to write the C++ source code to a file called hello.cpp. Then I proceed to compile the written file and execute the programme. Finally I include the output generated by the programme.

You need --shell-escape for the example to work.

\documentclass{article}
\usepackage{fancyvrb}
\begin{document}

\begin{VerbatimOut}{hello.cpp}
#include <fstream>

int main() {
  std::ofstream out;
  out.open("cpp-out.txt");

  out << "Hello World!" << std::endl;

  out.close();
  return 0;
}
\end{VerbatimOut}

\immediate\write18{g++ -o hello hello.cpp}
\immediate\write18{./hello}

\input{cpp-out.txt}

\end{document}

enter image description here

Other example

We can use this technique to include C code in a similar way (of course we need to use another compiler). In this example I exploit this to rapidly calculate factorials:

\documentclass{article}
\usepackage{fancyvrb}
\begin{document}

\begin{VerbatimOut}{fac.c}
#include <stdio.h>

long long factorial(int n) {
  if (n <= 1) return 1;
  return n*factorial(n-1);
}

int main(int argc, char* argv[]) {
  int n = atoi(argv[1]);
  printf("%lld\n", factorial(n));
  return 0;
}
\end{VerbatimOut}

\immediate\write18{gcc -o fac fac.c}

\newcommand\factorial[1]{%
  \immediate\write18{./fac #1 > /tmp/result.tex}%
  \input{/tmp/result.tex}%
}

\factorial{5}

\factorial{20}

\end{document}

enter image description here

Now the same code with lualatex, which will yield the same output:

\documentclass{article}
\usepackage{luacode}
\begin{luacode*}
function factorial(n)
  if (n <= 1) then
    return 1
  end
  return n*factorial(n-1)
end
\end{luacode*}
\begin{document}

\newcommand\factorial[1]{%
  \luaexec{tex.sprint(string.format("\%d", factorial(#1)))}%
}

\factorial{5}

\factorial{20}

\end{document}