Possible Duplicate:
Syntax Coloring in LaTeX

I want to add source code of my program in document but verbatim really bugs me. All that ugly fonts and stuff.

  • I cannot vote to close but I'm pretty certain such questions have been addressed previously (although I cannot find a best dup candidate).
    – chl
    Jun 27 '12 at 9:47
  • Is closing this question going to disable editing the answer which I marked as community wiki? I'm not sure if it is correct to mark this answer as community wiki though
    – interlude
    Jun 27 '12 at 9:53

I suggest using listings package.

For example







 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <limits.h>
 #include <math.h>

 typedef struct word //struct to contain words  
     char *string;
 } word;

 void print(int ** matrix, char str [], int n)
//this is a comment too long to fit on a line. So listings will break this line because I used \lstset{breaklines=true} But this is not default
     printf("--- %s ---\n",str);

     int i,j;
     for(i=1; i<=n; i++)
         for(j=1; j<=n; j++)
                 printf("%3d ",matrix[i][j]);
             else(printf("%3s ","INF"));



Produces this output with LaTeXExample with listings

As you can see \lstset{language=C++} defines the language in code. I prefer this approach because I think it is easier to read.

  • It's for reference actually. I repeatedly lost .tex file that contains this.
    – interlude
    Jun 27 '12 at 9:47
  • It's a shame that the standard solution for showing code in LaTeX looks so terribly ugly. May 10 '17 at 19:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.