我有一组预定义的 C 源代码文件,声明定义了许多静态函数 - 它们只是在 .c 文件中编码,而不是在任何 .h 头文件中声明。
现在我正尝试在我的 C++ 应用程序代码中使用这些函数:
Cmethods.c
static int amethod(int oppcheck)
{
}
使用 C 源代码文件创建库:
$ nm --demangle userlib.a | grep amethod
00000000000001b6 t amethod
CppApp.h
extern "C" { int amethod(int oppcheck); }
CppApp.cpp
#include "CppApp.h"
voit callme()
{
amethod(check);
}
然而,在确保 userlib.a 已链接的编译过程中,出现以下错误:
: undefined reference to `amethod'
$ nm --demangle userappcode.a | grep amethod
00000000000001b6 t amethod
U amethod
我的进一步发现是,对于 C 源代码文件中的函数,如果在 C 头文件中声明 - 它们的链接器错误永远不会发生。
请注意,我无法触及 C 源代码文件 - 它们由第三方社区提供,我们无法破坏许可。
我该如何解决这个问题
最佳答案
I have a set of pre defined C source code files that declares defines a lot of static functions.
Now I am trying to make use of those functions in my C++ application code:
从那些你想从其他一些函数调用的函数中删除 static
translation unit .
如果你不能这样做,你就不能从外部使用这些函数。编译器甚至可以将它们优化到将它们从目标文件中删除的程度。
(我不推荐的一个肮脏的技巧可能是用 gcc -Dstatic=
编译 C 代码,让预处理器什么都不替换 static
)
Note I cannot touch the C source code files.
那么你的任务是不可能完成的。
您可以“扩充”翻译单元,也许通过向它们附加一个public(非static
)调用static
的函数。例如,您可能会编译类似
// include the original C code with only `static`
#include "Cmethods.c"
// code a public wrapper calling the static method
extern int public_amethod(int oppcheck);
int public_amethod(int oppcheck) { return amethod(oppcheck); }
Note I cannot touch the C source code files - they are provided by third party community and we cannot break the license -
看起来您可能在法律上不允许编译该代码,或者您不能分发它的目标文件。 没有技术技巧可以克服法律禁令。如果在法庭上出现这种情况,您可能会输!
您的问题不是技术问题,而是社会和法律问题。您可能需要一名律师。您也可以与原始代码的提供者交谈,并询问他是否允许您做您想做的事情。
(没有更多的动机和背景,你的问题看起来很奇怪)
关于c++ - 在 C++ 应用程序代码中链接外部定义的静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48335107/