Skip to content

Instantly share code, notes, and snippets.

@djedr
Last active December 28, 2023 15:23
Show Gist options
  • Save djedr/96438f65d7e8996b34a0a9e5760b910e to your computer and use it in GitHub Desktop.
Save djedr/96438f65d7e8996b34a0a9e5760b910e to your computer and use it in GitHub Desktop.
Combining the C preprocessor and JavaScript

Note

This text is superseded by https://gist.github.com/djedr/7d21eac05ce2bbbca29b29d532a1fbe4.

Why

There are some reasons listed here. To expand on that, using the C preprocessor with JavaScript project also gives us an easy way to share constants between different files. Back-end (Node.js) and front-end (Angular, React). But you can also share constants between .js files and .css files or any other text formats. No fuss. Just #include "constants.cpp".

Macros that operate on plain text are more limited and sloppier than macros that operate on syntax trees, like sweet.js. But they are also simpler. And very often enough.

Also:

  • cpp is simple
  • anybody who wrote C, C++ or Objective-C used it and knows the basics
  • it's widely available
  • it's stable

How

Assuming you have the C preprocessor available from the command line under the cpp command, in order to invoke it in a JavaScript-friendly way, use it like so:

cpp input.cpp.js -P -nostdinc -o output.js

where:

  • input.cpp.js is the name of the to-be-preprocessed input file,

  • -P tells the preprocessor (quoting the manpage):

    Inhibit generation of linemarkers in the output from the preprocessor. This might be useful when running the preprocessor on something that is not C code, and will be sent to a program which might be confused by the linemarkers.

  • -nostdinc tells the preprocessor (quoting the man page):

    Do not search the standard system directories for header files. Only the directories you have specified with -I options (and the directory of the current file, if appropriate) are searched.

  • -o output.js specifies that the preprocessor's output will be written to a file named output.js

See the above link again to see more options you might want to pass to the command and cpp's man page for explaination of these.

Links

http://www.nongnu.org/espresso/js-cpp.html

https://rreverser.com/es6-modules-are-dead-long-live-c-preprocessor/

http://www.julienlecomte.net/blog/2007/09/16/

https://en.wikipedia.org/wiki/C_preprocessor

https://www.youtube.com/watch?v=3qK82JvRY5s ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment