次の方法で共有


How to escape a leading # within the C preprocessor

This is probably a no-brainer for most people, but for some reason I banged my head against the wall for about an hour trying to figure this one out.

Background

Oftentimes you have source files (or in our case aspx files) that contain common headers, footers, sections, etc. Instead of paying the runtime hit of dynamically including things within the page, we just use the C preprocessor to #define macros that get expanded at build time. For example, do you ever get sick of writing the <!DOCTYPE> at the top of the page or want to make sure that it's consistent across all of your pages? Well, it's easy to do if you use a C preprocessor macro:

#define XHTML_DOCTYPE_DECLARATION <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> \ <html xmlns="https://www.w3.org/1999/xhtml">

Then in your .aspx page simply do this:

XHTML_DOCTYPE_DECLARATION

and voilà.

Problem

Well, what if you have something like this in your .aspx.pp page (we use a .pp extension to indicate that it's a C preprocessor file that will get renamed after the preprocessor runs):

<style type="text/css"> #element { background-color: white; } </style>

The C preprocessor will barf at you and say something like the following:

fatal error C1021: invalid preprocessor command 'element'

Solution

There are a couple different ways of fixing this, although I think the simplest way is to just define a macro that just passes through its argument, like this:

#define IGNORE_HASH(x) x

Then you change the code to this:

<style type="text/css"> IGNORE_HASH(#element) { background-color: white; } </style>

Now the C preprocessor ignores the #element and everything works as expected.

Comments

  • Anonymous
    April 23, 2008
    Ever heard of server side includes? They look like this: <!--#include virtual="/path_doctype_def" --> SSI have been around for something like 12 years, and last time I checked were still supported in asp.net

  • Anonymous
    April 23, 2008
    The comment has been removed