How can I show code (specifically C++) in an HTML page?
Asked Answered
F

3

15

How can I show code in a website using HTML? Basically, I have a C++ program that I'd like to share on my website and I want to show it in the page.

Is there anyway to show a C++ code in HTML other than using HTML text?

Fulminant answered 19/4, 2011 at 0:14 Comment(2)
explain... do you want syntax highlighting? or what?Persevere
If you use Doxygen, you can have functions link to each otherSlimsy
P
12

HTML includes a tag called <code>, which is meant for the purpose you describe.

The spec even includes an example class name convention to indicate which language the code is in:

<pre><code class="language-pascal">var i: Integer;
    begin
        i := 1;
    end.</code></pre>

I don’t know of any web browser that supports such a convention (come on, Chrome), but the JavaScript syntax highlighters mentioned in other answers could use it to work their magic.

As you can see in the example, the <code> tag is usually wrapped in the <pre> tag, which preserves white space, which is often important for code.

Philbo answered 19/4, 2011 at 0:22 Comment(0)
O
9

You can use SyntaxHighlighter. It will unobtrusively enhance code samples on your page with specific syntax highlighting for a wide range of languages.

Here's an example for C++

<head>
  <link href="css/shCore.css" rel="stylesheet" type="text/css" />
  <link href="css/shThemeDefault.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <pre class='brush: cpp'>
  // my first program in C++
  #include <iostream>
  using namespace std;

  int main ()
  {
    cout << "Hello World!";
    return 0;
  }
  </pre>

  <script src="js/shCore.js"></script>
  <script src="js/shBrushCpp.js"></script>
  <script>
    SyntaxHighlighter.all()
  </script>
</body>
Opisthognathous answered 19/4, 2011 at 0:15 Comment(1)
It seems a shame to put code in an HTML page without using the <code> tag.Philbo
V
9

There are various syntax highlighters out there. Google Code Prettify is a pretty good one. (Good enough for Stack Overflow to use, anyway.)

Vying answered 19/4, 2011 at 0:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.