This technique involves utilizing a separate file for each data type, while also enabling the inclusion of specially formatted javascript files in a C/C++ header.
In C/C++, you have the ability to use #define
macros to modify identifiers as required. In the case of javascript, a suitable candidate for this is var
since it serves a specific purpose in javascript ... allowing for flexibility to redefine it to match any c type. Typically, using new Array()
in javascript isn't recommended, but due to the disparity between array initialization syntax in C/C++ ({...}
) and javascript ([...]
), it becomes necessary to employ this workaround in order to encapsulate arrays.
c-header.h
//constant integers
#define var const int
#include "int-consts.js"
#undef var
//constant strings
#define var const char*
#include "string-consts.js"
#undef var
//arrays of strings
#define var const char**
#define new (const char*[])
#define Array(...) {__VA_ARGS__}
#include "string-arrays.js"
#undef new
#undef var
//and so forth for other types
int-consts.js
var swapMagicOffset = 4086;
string-consts.js
var swapMagic = "SWAP-SPACE";
var swapMagic2 = "SWAPSPACE2";
string-arrays.js
var cars = new Array("Ford", "Chevy", "Dodge");
Edit:
Upon further analysis, it becomes apparent that beyond simply aligning constants, there are opportunities to create code that can function seamlessly in both javascript and C by leveraging a lesser-known distinction between the two languages. In C, one can utilize '\' to continue onto the next line, allowing for constructs like *\newline/
to denote the end of a comment in C (using -Wno-comment during compilation with Clang to bypass warnings), whereas such syntactic nuances do not apply in javascript, thereby extending the commented section until encountering an actual '*/' token.
/* The C comment concludes with '/' on the next line, transitioning into a continued js comment block *\
/ //BEGIN C Block
#define function int
/* This marks the conclusion of the original js comment, but introduces an initial '/*' for C */
/*The majority of compilers support K&R-style C with parameters structured as follows:*/
function volume(x,y,z)/**\
/int x,y,z;/**/{return x*y*z;}
/**\
/
#undef function
/**/