外部"C"编译目标代码中的函数 [英] extern "C" functions in compiled object code

查看:162
本文介绍了外部"C"编译目标代码中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境是Microsoft Visual C ++ 2015和Windows 7.

Environment is Microsoft Visual C++ 2015 and Windows 7.

在标头中定义的inline extern "C"函数是否有特殊之处?我正在使用其中其中一个标头包含此类野兽的SDK.在我的应用程序中,我有一个单独的TU(转换单元),其唯一的工作就是包含上述标头.就这样.没什么其他的了.如果我深入研究生成的目标文件,则会看到引入了extern "C"函数.这使我产生了一些不必要的副作用(我暂时不考虑它们的含义,因为这可能会分散主要问题的注意力).

Is there anything special about inline extern "C" functions defined in a header? I am consuming an SDK in which one of the headers contain such a beast. In my application I have a lone TU (translation unit) whose only job in life is to include the aforementioned header. That's all. Nothing else is in it. If I dig into the generated object file, I see the extern "C" function being pulled in. This is causing me some unwanted side effects (I will leave out what they are for now, as it might just distract from the main issue).

为什么会这样?客户端代码中没有任何东西(请记住我唯一的TU是空的,除了main()入口点和标头)触发了这种情况.

Why would this happen? There is nothing from the client code (remember my lone TU is empty except for main() entry point and that header) that is triggering this to happen.

UPDATE 带有一个小片段,可能会更好地解释我遇到的问题:

UPDATE with a small snippet that might explain better what I am running into:

这是实际发生的情况:

FooObj::FooObj() { }

FooObj::~FooObj() { CallIntoAnotherC_API(); }

SDKHeader.h

#include <FooObj.h>

extern "C" inline void SomeFunc(void* user_data)
{   
    A* obj = static_cast<A*>(user_data);
    obj->CallAnotherFunc(FooObj(33));
}

MyFile.cpp

#include "SDKHeader.h"

int main() { return 0; }

将MyFile.cpp编译为可执行文件失败,链接器抱怨 CallIntoAnotherC_API是一个未解决的外部.

Compiling MyFile.cpp into an executable fails with the linker complaining that CallIntoAnotherC_API is an unresolved external.

推荐答案

乔纳森·莱夫勒(Jonathan Leffler)!非常感谢您为我指明了正确的方向.我发现了问题所在,至少可以说它很奇怪.在我上面发布的SDKHeader.h代码段中,有一个SomeFunc的无关声明,如下所示:

Jonathan Leffler! Thank you very much for pointing me in the right direction. I found out what the problem is and its super weird to say the least. In the SDKHeader.h snippet I posted above, there is an extraneous declaration of SomeFunc like so:

#include <FooObj.h>

// I don't know why this declaration exists but its presence is
// causing the compiler to include SomeFunc and everything it references
// in the object file causing eventual linker errors! Also notice that
// this declaration even misses the "inline" keyword.
extern "C" void SomeFunc(void* user_data);

extern "C" inline void SomeFunc(void* user_data)
{   
    A* obj = static_cast<A*>(user_data);
    obj->CallAnotherFunc(FooObj(33));
}

删除此无关的声明将消除链接器错误,并防止伪造的符号显示在目标文件中.

Removing this extraneous declaration gets rid of the linker errors and also prevents the bogus symbol from showing up in the object file.

这篇关于外部"C"编译目标代码中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆