此方法对每种数据类型使用单独的文件,但允许您在 C/C++ 标头中包含特殊格式的 javascript 文件。
您可以在 C/C++ 中使用 #define 宏来根据需要更改标识符。对于 javascript,显而易见的候选者是 var,因为它仅在 javascript 中需要......它可以根据任何 c 类型的需要重新定义。通常我不建议在javascript中使用new Array(),但是由于C/C++使用{...}来初始化数组,而javascript使用[...],这是一个必要的邪恶,允许你包装它们。
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";
字符串数组.js
var cars = new Array("Ford", "Chevy", "Dodge");
编辑:
进一步考虑,您可以做的不仅仅是保持常量同步。您甚至可以使用两种语言之间鲜为人知的差异编写可以同时作为 javascript 和 C 运行的代码。在 C 中,您可以使用在下一行继续的 '\',从而允许我们使用 *\newline/ 结束 C 中的注释(使用 -Wno-comment 编译以忽略 Clang 中的警告),但由于 js 不遵循相同的规则,它会一直作为注释继续,直到找到实际的 '*/' 标记。
/* C comment ends with the '/' on next line but js comment is open *\
/ //BEGIN C Block
#define function int
/* This ends the original js comment, but we add an opening '/*' for C */
/*Most compilers can build K&R style C with parameters like this:*/
function volume(x,y,z)/**\
/int x,y,z;/**/{return x*y*z;}
/**\
/
#undef function
/**/