我试图从 C++ 调用汇编函数,链接器说我尝试调用的函数不存在。这是错误:
avr-gcc -mmcu=atmega328 -Wall -o main.elf hello.S main.cpp
/tmp/ccS7uaAX.o: In function `main':
main.cpp:(.text+0x14): undefined reference to `hello(char, char, char, char, char)'
collect2: error: ld returned 1 exit status
这是我的来源:
//Somewhere in hello.S
.global hello
hello:
ret
//In main.cpp
extern void hello(char, char, char, char, char);
int main(){
hello(1, 2, 3, 4, 5);
}
如果这有帮助,这里是我将文件编译成目标文件后的反汇编:
这是 main.o:
00000000 <main>:
0: 0f 93 push r16
2: cf 93 push r28
4: df 93 push r29
6: cd b7 in r28, 0x3d ; 61
8: de b7 in r29, 0x3e ; 62
a: 05 e0 ldi r16, 0x05 ; 5
c: 24 e0 ldi r18, 0x04 ; 4
e: 43 e0 ldi r20, 0x03 ; 3
10: 62 e0 ldi r22, 0x02 ; 2
12: 81 e0 ldi r24, 0x01 ; 1
14: 0e 94 00 00 call 0 ; 0x0 <main>
18: 80 e0 ldi r24, 0x00 ; 0
1a: 90 e0 ldi r25, 0x00 ; 0
1c: df 91 pop r29
1e: cf 91 pop r28
20: 0f 91 pop r16
22: 08 95 ret
这里是 hello.o:
00000000 <hello>:
0: 08 95 ret
我已经搜索了几个小时了,我真的不知道发生了什么。
每个文件都是单独编译的,我认为这只是链接搞砸了。
我也可以毫无问题地编译纯汇编。
任何帮助将不胜感激,我刚刚开始考虑为 AVR 混合汇编和 C++。
最佳答案
试试这个:在 main.cpp 中,
extern "C" void hello(char, char, char, char, char);
其中有一个“C”
。 C++ 更改函数名称以包含其类型,称为 name mangling 。 “C”告诉编译器不要破坏。汇编器不会损坏,因此编译器需要知道不要这样做。
顺便说一句,链接器通过重整来告诉您它正在查找的 hello
的参数类型。
编辑 在当前目标文件上执行strings main.o |grep hello
,您将看到对 hello 的引用,后面带有各种有趣的字符。这是被破坏的名字。
关于c++ - AVR-GCC 未将 C++ 与汇编函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39934392/