Incorrect link in C program and Assembly

Asked

Viewed 56 times

1

I did an Assembler routine to calculate the exponential. I compiled it, and I get the Object Exp file. o

The C++ program to take advantage of this routine is the type of:

#include <iostream>
#include <math.h>

using namespace std;

namespace myns {
  extern "C" float exp(float x);  // para linkar com a rotina de exp.o
}

int main() {
  cout << exp(1.0) - myns::exp(1.0) << "\n";
  return (0);
}

To compile I do something like:

g++ myfile.cpp exp.o -o myfile

And it seems that most of the time the myns::Exp function links with the standard C library function Exp (stdlib)... And in fact, I need C stdlib for my program...

Can you define the namespace in the Assembler (gcc)? Does anyone know how to force the right link without changing the function name from Exp to myexp, e.g.? This would imply changing the Assembler...

1 answer

0


The GCC has a extension which allows you to define the symbol name of a variable or function, in this way you can use a different name for the function but access the same symbol. Simply declare the function in this way:

extern "C" float my_exp(float x) asm("exp");

So in the source code you use the function as my_exp, but the compiler will use the symbol exp for this function.

  • And will you link to the correct "Exp" function? From my. o object file, not "Exp" from the standard C library?

  • @Jdias yes, because the symbols are different since C++ follows a different formatting to name the symbols of its functions. Hence the extern "C" is used when declaring the prototype of a function written in C.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.