在 Qt 中的 C++ 中添加 C 函数时出现问题

build issue when adding C function inside C++ in Qt

我正在构建一个 Qt/C++ 应用程序。此应用程序必须通过 MTP 连接到 android 设备。在 mtp 复制期间,我必须向 MTP API(C-only)

提供 C 回调

我已经在下面声明了这个回调:

DeviceMngr.cpp

int fileprogress(const uint64_t sent, const uint64_t total, void const * const data) {
    int percent = (sent * 100) / total;

    if (Transfer_Cancelled == true)
        return 1;

    return 0;
}

DeviceMngr.h

extern  bool Transfer_Cancelled;

extern "C" {    
int fileprogress(const uint64_t sent, const uint64_t total, void const * const data);
}

并在下面的方法中调用:

uint32_t DeviceMngr::CreateFile(QString filename, uint32_t parent_id) {
...
    ret = LIBMTP_Send_File_From_File(Device->device, strdup(AbsolutePath), genfile, fileprogress, NULL);
...

Transfer_Cancelled的用法是:

void DeviceMngr::CancelTransfer() {
    Transfer_Cancelled = true;
}

DeviceMngr::DeviceMngr()
{
    ...
    Transfer_Cancelled = false;
}

并且还在方法实例化中确保它初始化为 false。

这是问题所在:

Undefined symbols for architecture x86_64:
  "_Transfer_Cancelled", referenced from:
      DeviceMngr::DeviceMngr() in devicemngr.o
      DeviceMngr::CreateFile(QString, unsigned int) in devicemngr.o
      _fileprogress in devicemngr.o
      DeviceMngr::CancelTransfer() in devicemngr.o
ld: symbol(s) not found for architecture x86_64

TransferCancel 仅定义 DeviceMngr.c 和任何其他地方。

有什么想法吗?

与函数无关,问题出在变量Transfer_Cancelled上。这是一个问题,因为您在头文件中 define 它,并且由于您在头文件中定义了它,它将在头文件所在的所有源文件 (translation units) 中定义包括在内。

您应该只声明头文件中的变量,例如

extern bool Transfer_Cancelled;

添加ifndef以避免多个include

#ifndef FOO_H                                                
#define FOO_H
extern "C" {
    bool Transfer_Cancelled;

    int fileprogress(const uint64_t sent, const uint64_t total, void const * const data);
}  
#endif