我有一个C++项目,使用了一个C bison解析器。该C解析器使用一个函数指针结构体来调用函数,在bison减少产生式时创建适当的AST节点:
typedef void Node;
struct Actions {
Node *(*newIntLit)(int val);
Node *(*newAsgnExpr)(Node *left, Node *right);
/* ... */
};
现在,在项目的C++部分,我填充这些指针。
class AstNode {
/* ... */
};
class IntLit : public AstNode {
/* ... */
};
extern "C" {
Node *newIntLit(int val) {
return (Node*)new IntLit(val);
}
/* ... */
}
Actions createActions() {
Actions a;
a.newIntLit = &newIntLit;
/* ... */
return a;
}
现在我把它们放在extern "C"
中的唯一原因是我希望它们具有C调用约定。但是最理想的情况是,我希望它们的名称仍然被混淆。它们从未被C代码按名称调用,因此名称混淆不是问题。将它们混淆将避免名称冲突,因为某些操作被称为error
,而C++回调函数具有丑陋的名称,只是为了避免与其他模块发生名称冲突。
extern "C" {
void uglyNameError(char const *str) {
/* ... */
}
/* ... */
}
a.error = &uglyNameError;
我想知道是否仅通过给函数类型C链接就可以实现
extern "C" void fty(char const *str);
namespace {
fty error; /* Declared! But i can i define it with that type!? */
}
有什么想法吗?我正在寻找标准C++解决方案。