[英]Trying to compile Assembly + C++ with MinGW: ccqKAvXJ.o:main.cpp:(.text+0x18): undefined reference to `GetMagicNumber'
I have this simple sample: 我有一个简单的示例:
main.cpp: main.cpp中:
#include <iostream>
extern "C" int GetMagicNumber();
int main(void)
{
std::cout << "The magic number is: " << GetMagicNumber();
return 0;
}
functions.s: functions.s:
.section .text
.global GetMagicNumber
GetMagicNumber:
movl $42, %eax
ret
and build.bat: 和build.bat:
C:\Qt\Qt5.2.0\Tools\mingw48_32\bin\as functions.s -o functions.o
C:\Qt\Qt5.2.0\Tools\mingw48_32\bin\g++ functions.o main.cpp -o MagicNumber.exe
or 要么
C:\Qt\Qt5.2.0\Tools\mingw48_32\bin\gcc functions.s main.cpp -lstdc++ -o MagicNumber.exe
When I try to compile with MinGW 4.8. 当我尝试使用MinGW 4.8进行编译时。 I get: 我得到:
C:\Qt\Qt5.2.0\Tools\mingw48_32\bin\gcc functions.s main.cpp -lstdc++ -o MagicNumber.exe
C:\Users\...\Local\Temp\ccqKAvXJ.o:main.cpp:(.text+0x18): undefined reference to `GetMagicNumber'
collect2.exe: error: ld returned 1 exit status
I've read a few tutorials and I watched videos and I still cannot figure out what I am doing wrong. 我已经阅读了一些教程,并且观看了视频,但仍然无法弄清自己做错了什么。 Why do I get that undefined reference error? 为什么会出现未定义的参考错误?
External scope C symbols have a leading underscore, so try: 外部范围C符号的下划线开头,因此请尝试:
.section .text
.global _GetMagicNumber
_GetMagicNumber:
movl $42, %eax
ret
EDIT if you want to make the code more platform-agnostic, I use the following macro, where the assembler file has a .S
extension which is processed by the C compiler, allowing the pre-processor to play along: 如果想使代码与平台无关,请进行编辑 ,我使用以下宏,其中的汇编文件具有.S
扩展名,该扩展名由C编译器处理,从而允许预处理器进行播放:
#ifdef __APPLE__
#define NAME(name) _##name
#else
#define NAME(name) name
#endif
.globl NAME(GetMagicNumber);
NAME(GetMagicNumber):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.