简体   繁体   English

从C ++到C文件中定义的变量/函数的未定义引用

[英]Undefined reference from C++ to variables/functions defined in C file

I've been given a package of files (one .cpp, and some .c and .h) and want to make some modifications. 我得到了一个文件包(一个.cpp以及一些.c和.h),并且想要进行一些修改。 But right now I'm just trying to get the original version to compile (in Linux). 但是现在我只是想让原始版本可以编译(在Linux中)。

Here's a (really) minimal working example: 这是(确实)最小的工作示例:

mainfile.cpp mainfile.cpp

extern "C"{
#include "auxfile.h"
}

int main(int argc, char * argv[]){
getfoo(temperature);
return 0;}

auxfile.h auxfile.h

#define PUBLIC
#define PRIVATE static
extern int temperature;
int   getfoo(  int inputint);

auxfile.c auxfile.c

#include "auxfile.h"
int temperature = 37;
PUBLIC int getfoo(  int inputint){
return 7;
}

When I type 当我打字

g++ mainfile.cpp

I get 我懂了

mainfile.cpp(.text+0x11): undefined reference to `temperature'
mainfile.cpp(.text+0x18): undefined reference to `getfoo'
collect2: ld returned 1 exit status

For what it's worth, I've looked through numerous "undefined reference" questions and spent dozens of hours working on my own. 对于它的价值,我浏览了许多“未定义的参考”问题,并花费了数十个小时独自工作。 The above code presents the essence of the problem. 上面的代码介绍了问题的实质。 Any help would be massively appreciated. 任何帮助将不胜感激。 Thanks. 谢谢。

At the time of linking, all symbols (except those for dynamic linking, aka shared libraries) have to be defined. 链接时,必须定义所有符号(动态链接,共享库除外)。 To create an object file with possibly unresolved symbols for later linking, there is the -c flag, that means just compile, do not link . 要创建带有可能无法解析的符号以供以后链接的目标文件,请使用-c标志,这意味着仅进行编译而不进行链接

So, the following would work: 因此,以下方法将起作用:

g++ -c -omainfile.o mainfile.cpp
gcc -c -oauxfile.o auxfile.c
g++ -o mainfile mainfile.o auxfile.o

Only the last line actually invokes the linker and as you have both object files, all symbols are found. 实际上只有最后一行调用了链接器,并且由于您拥有两个目标文件,因此会找到所有符号。

Just for completeness, in a real-world scenario you'd handle compiling and linking using make . 仅出于完整性考虑,在现实世界中,您将使用make处理编译和链接。 Create a Makefile with the following contents: 创建具有以下内容的Makefile

OBJS:= mainfile.o auxfile.o

all: mainfile

# $@ means what to build (in this case "mainfile"), $^ is replaced by all
# dependencies (here the contents of the variable OBJS)
mainfile: $(OBJS)
        g++ -o$@ $^

# pattern for *.cpp -> create a *.o file with same name using g++
%.o: %.cpp
        g++ -c -o$@ $<

# the same for *.c, but using gcc here
%.o: %.c
        gcc -c -o$@ $<

clean:
        rm -f $(OBJS)

# "PHONY" are targets, that are not actually the names of output files
.PHONY: all clean

Then just type make and see the "magic" happening. 然后只需键入make并查看发生的“魔术”。 Of course this is just for starters, no dependencies are tracked etc... 当然这只是针对初学者的,不会跟踪任何依赖项等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM