1

我有 ac b.cpp 文件。

/****** a.c ******/
fun1(...)
{
     ..........

     fun2(...); /* function present in b.cpp */

     ..........
}

/******* b.cpp *******/
extern "C" int fun2(...);
int fun2(...)
{
    ..........

}

我编译的代码如下:

a.o:a.c b.o
    gcc -c -o a.o a.c b.o

b.o:b.cpp
    g++ -c -o b.o b.cpp

但我收到错误,因为未定义对“fun2()”的引用。这是正确的编译方式还是我需要更改任何内容。?

4

3 回答 3

5

你需要在ac中添加函数的原型

于 2013-07-15T05:22:22.597 回答
3
extern "C" int fun2(...);

您在 b.cpp 中有该行定义函数,它告诉它使函数具有“C”链接,但是您在 ac 中没有相应的原型来告诉它该函数存在。

/****** a.c ******/
extern int fun2(...);
fun1(...)
{
     ..........

     fun2(...); /* function present in b.cpp */

     ..........
}

会修复它。或者放在标题中

// b.h
#pragma once

// tell c++ you want these externs to have C linkage
#ifdef __cplusplus
extern "C" {
#endif

// list your "C" accessible functions here.
extern int fun2(...);

// end the extern scope
#ifdef __cplusplus
};
#endif

// a.c
#include "b.h"

// b.cpp
#include "b.h"
于 2013-07-15T05:23:12.983 回答
1

为什么要从目标文件构造目标文件?您不需要将 bo 链接到 ao,只需从其相应的 c 构建每个对象并在最后链接所有内容(使用您的 main() 函数)。

于 2013-07-15T05:30:07.127 回答