c - C 中 undefined reference 错误 外部汇编包含在 C 中

标签 c assembly

我将外部 asm 包含到 c 中,当我尝试编译时出现错误。

我正在编译这样的c文件 - g++testing.c

错误:

cc0FHCkn.o:testing.c:(.text+0xe): undefined reference to helloWorld collect2.exe: error: ld returned 1 exit status

C 代码:

#include<stdio.h>
extern "C" int helloWorld();
int main() {
    printf("Its - ",helloWorld());
}

ASM代码:

.code
helloWorld proc
    mov rax, 123
    ret
helloWorld endp
end

最佳答案

注意:我使用这个答案是为了能够通过评论和使用 gcc 表达更多内容。

首先,仅执行g++testing.cg++无法链接到未指定的汇编程序文件,因此当然缺少helloWorld

<小时/>

如果我有文件hw.c:

int helloWorld()
{
  return 123;
}

我要求通过选项-S生成源汇编程序(我还使用-O来减少汇编程序源代码的大小),所以我不必编写手动汇编文件,我确信它与gcc兼容:

/tmp % gcc -O -S hw.c

生成了文件hw.s:

/tmp % cat hw.s
    .file   "hw.c"
    .text
.globl helloWorld
    .type   helloWorld, @function
helloWorld:
.LFB0:
    .cfi_startproc
    movl    $123, %eax
    ret
    .cfi_endproc
.LFE0:
    .size   helloWorld, .-helloWorld
    .ident  "GCC: (GNU) 4.4.7 20120313 (Red Hat 4.4.7-16)"
    .section    .note.GNU-stack,"",@progbits
/tmp % 

还有文件m.c:

#include <stdio.h>

extern int helloWorld();

int main()
{
  printf("%d\n", helloWorld());
  return 0;
}

我能做到:

/tmp % gcc m.c hw.s
/tmp % ./a.out
123
<小时/>

我建议您执行相同的操作,用 C 语言编写 helloWorld,然后使用选项 -S 生成汇编程序,这样做您一定会遵循函数定义中的 gcc 要求

关于c - C 中 undefined reference 错误 外部汇编包含在 C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54709046/

相关文章:

c - ZLIB中有fmemopen()吗

assembly - 函数式汇编语言

坐标传递给 XDrawImageString()

c - 检测静态库是否为瘦存档

C - 在实际问题点之前提出的段错误

assembly - MIPS 组装中的奇怪跳跃

assembly - 汇编器字符输出

c - Dos 中断处理程序锁定程序

c++ - 调用 Windows API 内联汇编的问题

c函数链接可能吗?