【问题标题】:build issue when adding C function inside C++ in Qt在 Qt 中的 C++ 中添加 C 函数时的构建问题
【发布时间】:2015-05-28 07:07:11
【问题描述】:

我正在构建一个 Qt/C++ 应用程序。此应用程序必须通过 MTP 连接到安卓设备。在 mtp 复制期间,我必须向 MTP API 提供 C 回调(仅限 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;
}

并且还在方法实例化中确保它的 init 为 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 和其他任何地方。

有什么想法吗?

【问题讨论】:

  • 你多次包含标题

标签: c++ c qt callback


【解决方案1】:

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

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

extern bool Transfer_Cancelled;

【讨论】:

  • 我已经这样做了,我已经在同一个标​​题中声明了 Transfer_Cancelled 但在 extern "C" {
  • 我已经更改了描述中的代码并更改了构建问题
  • @Seb 您仍然需要定义变量。在一个源文件中定义它。
  • 我将 extern bool.. 从头文件移动到 cpp 文件,但仍然是同样的问题
  • @Seb 将extern bool Transfer_Cancelled; 保留在头文件中,并在源文件中添加bool Transfer_Cancelled = false;。头文件中声明,源文件中定义。
【解决方案2】:

添加ifndef以避免多次包含

#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

【讨论】:

  • 包含守卫只防止在单个源文件中包含多个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 2011-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
相关资源
最近更新 更多