C ++,extern和GCC

时间:2016-12-01 18:41:14

标签: c++ c gcc

我有以下情况,

文件1:main.c

extern void afunction(int);

int main()
{
   afunction(0);
}

文件2:other.cpp

void afunction()
{
   // do some crazy stuff.
   return; 
}

如何将这两个文件链接在一起,以便在编译器尝试查找函数()时呢?

注1:我不能使用#include“other.cpp”

注意2:除非别无选择,否则我不想创建库。

-

我尝试了以下gcc命令,但它提供了未定义的引用。

gcc other.cpp main.c 

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

将main.c重命名为main.cpp

新文件,other.h

#ifndef other_H
#define other_H


void afunction();

#endif

然后在main.cpp中添加#include

#include "other.h"

int main()
{
   afunction();
}

请注意,empunction()的声明和定义匹配很重要,因此额外的头文件也是如此。处理复杂到足以存在于两个文件中的内容时,请始终使用函数声明添加头文件,或切换到另一种语言。这就是c / c ++如何运作超过25年。