c++ - 如何告诉 g++ 链接器在 x86-64 程序集(目标文件)中实现了一个外部添加函数?

标签 c++ ubuntu x86-64 nasm simd

我很困惑为什么链接器不链接到目标文件中的函数。

我用 x86-64 汇编语言实现了一个函数,并通过 -f elf64 生成了一个目标文件。 (Ubuntu 是我的目标操作系统。) 目标文件已成功生成,但尝试使用上述目标文件编译我的 C++ 项目会导致链接器找不到我定义的函数(在目标文件内)。 编译是这样完成的:

g++ -W -Wall -pedantic -g -std=c++17 main.cpp SSE_Ubuntu_Tuple.cpp SSE_Ubuntu_Tuple.o -o test
#ifndef MATH_TUPLE_HPP
#define MATH_TUPLE_HPP

namespace Math
{
    struct Tuple
    {
        float components[4]; // x, y, z, w
        Tuple(float, float, float, float);
        Tuple operator+(Tuple&) const;
    }; // struct Tuple
} // namespace Math

#endif // MATH_TUPLE_HPP
section .text
global sse_ubuntu_tuple_add

; rdi = &x, rsi = &y

sse_ubuntu_tuple_add:
    movdqa xmm0, [rdi] ; xmm0 = *rdi
    addps xmm0, [rsi] ; *rdi + *rsi
    movdqa [rdi], xmm0 ; *rdi = xmm0
    ret

#include "Tuple.hpp"
#include <algorithm>

namespace Math
{
    extern void sse_ubuntu_tuple_add(float[4], float[4]);

    Tuple::Tuple(float t_x, float t_y, float t_z, float t_w) : components{t_x, t_y, t_z, t_w} {}
    Tuple Tuple::operator+(Tuple& t_rhs) const
    {
        float sum[4]{};
        constexpr int number_of_components = 4;
        std::copy(components, components + number_of_components, sum);
        sse_ubuntu_tuple_add(sum, t_rhs.components);
        return Tuple(sum[0], sum[1], sum[2], sum[3]);
    }
} // namespace Math

我期望没有错误的链接和编译。

最佳答案

您需要将 sse_ubuntu_tuple_add 声明为 extern "C":

extern "C" void sse_ubuntu_tuple_add(float[4], float[4]);

此外,在某些系统上,您可能需要在程序集文件中创建带有前导下划线的符号:_sse_ubuntu_tuple_add

编辑:显然,对于 ELF,您不需要前导下划线。

关于c++ - 如何告诉 g++ 链接器在 x86-64 程序集(目标文件)中实现了一个外部添加函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56234043/

相关文章:

c++ - 是否可以在不扩展模板参数包的情况下对其进行 "store"处理?

c++ - boost::algorithm - 拆分字符串返回一个额外的标记

ubuntu - 您无权访问此服务器上的/。 (AWS EC2 Ubuntu Laravel 项目)

php - Apache 2.22 + php 5.40 + Symfony Framework = Apache Segmentation fault (11)

linux - 内存使用 : Program allocates too much memory

x86 - 是否可以设置在 cpu 写入特定地址时中断的中断?

linux - 无法访问相对于 CANVAS 小部件的鼠标坐标

c++ - 用于磁盘支持的关联数组的 SQLite?

c++ - if 语句与 if-else 语句,哪个更快?

c - 是否有可能中断一个进程并检查它以便稍后恢复它?