c++ - 调用 C 头文件时出现链接错误

标签 c++ c qt linker extern

我正在从我用 Cpp 编写的 Qt 中编写的头文件调用 C 函数。当我尝试编译 Qt 应用程序时,我不断收到链接错误。

这是头文件:

#ifndef GROUND_SERVER_H
#define GROUND_SERVER_H


#ifdef __cplusplus
extern "C" {
#endif

struct system_info{
    char id[33];
};

/*  Support function for the below function */
    void Generate_Key(char*,char*,char*);

/*  Runs the actual key generation as well as 
    moves the file to the respectful card or
    USB drive inserted in the system that will
    act as the user system key  */ 
void run_key_generation(struct system_info*,char*,char*);

/*  Function to run the server on a selected 
    port at which the medium that the server 
    is to listen on will be connected.  */
void run_server(unsigned short);

void generate_id();

#ifdef __cplusplus
};
#endif


#endif

最佳答案

#include "foo.h" 只是将 foo.h 的内容文本包含到当前编译单元中。如果您在不同的文件中实现一个函数,那么您也需要编译该文件,并链接生成的目标文件以形成可执行文件(或库)。

这也适用于混合 C 和 C++(或大多数其他编译的)代码:您使用适合其编写语言的编译器来编译源代码文件,最后将所有内容链接在一起。

所以:

foo.h

#ifndef FOO_H
#define FOO_H 1
#ifdef __cplusplus
extern "C" {
#endif

int answer(void);

#ifdef __cplusplus
}
#endif
#endif

foo.c

int answer(void) {
  return 42;
}

bar.cc

#include <iostream>
#include "foo.h"

int main(int argc, char ** argv) {
  std::cout << "The answer is " << answer() << std::endl;
  return 0;
}

要从这些文件创建可执行文件,您需要:

gcc -c foo.c   # Compile C file
g++ -c bar.cc  # Compile C++ file
g++ -o foobar foo.o bar.o # Link

关于c++ - 调用 C 头文件时出现链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35183698/

相关文章:

c - 为什么 "const int*"可以指向一个非常量 int?

c - 文件描述符和套接字文件描述符的区别

c++ - Linux下的Qt资源

c++ - opencv的Qt dll错误

c++ - 该代码标准是否合规?

c++ - 静态对象(Effective C++ 第三版中的第 4 项)

c - 每 x 分钟更新一次变量

c++ - 无法打印 signed int 类型的大小

c++ - 运算符重载导致模板参数推导失败

c++ - 如何解决 mac 中的 qt5(未找到软件包)cmake 错误?