-1

So i wrote a small program just to test if everything is working. It should take two inputs und output them summed up.

test.cpp:

#include <iostream>
#include <stdio.h>

extern "C" int test(int a, int b);

int main(){
    int x = 0;
    std::cout << test(10, 20);
    std::cin >> x;
    return 0;
}

test.s:

.global test

test:

    mov %eax, %ecx
    add %eax, %edx

    ret

I then tried compiling it with g++: g++ -o main.exe test.cpp test.s But i get an error: undefined reference to `test'

I am completely new to programming with assembly. Any advice?

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
Xaverrrrr
  • 35
  • 8
  • Your compilation command only compiles "test.cpp", but you also need to compile and link "test.s" in order to have the reference to `test` be resolved – UnholySheep Oct 02 '22 at 15:31
  • @UnholySheep Compiling g++ -o main.exe test.cpp test.s results in the same error – Xaverrrrr Oct 02 '22 at 15:35
  • What OS are you on? – Michael Petch Oct 02 '22 at 15:35
  • @MichaelPetch I am using Windows 11 – Xaverrrrr Oct 02 '22 at 15:36
  • 2
    I assume with MinGW targeting 32 bit windows program? If so you will need to add an `_` (underscore) to the assembly code labels that are to bee visible to other objects. So you'd be use `_test:` . The `_` is part of the naming convention in Wi32 COFF objects and win32 executables. – Michael Petch Oct 02 '22 at 15:36
  • 1
    @MichaelPetch With the underscore it works, thanks so much! – Xaverrrrr Oct 02 '22 at 15:39
  • 2
    Does this actually result in the desired value? It seems like AT&T syntax with the percent sign identifiers but the register operand order seems like Intel syntax. – ecm Oct 02 '22 at 15:47

1 Answers1

1

You have to include test.s file in your build command:

g++ -o main.exe test.cpp test.s

otherwise the compiler will complain that the test function is undefined because it cannot find it

pqnet
  • 6,070
  • 1
  • 30
  • 51
  • Sorry, pasted the wrong command in my question. Your awnser is the command i used, it results in the same error – Xaverrrrr Oct 02 '22 at 15:32
  • it looks like you have problems with your installed g++ version then. Add some details such as the operating system, and the result of running `g++ --version` and `g++ -v` – pqnet Oct 02 '22 at 15:38
  • 2
    No problem with his g++ version. He's using a Win32 g++ tool chain so the additional issue is the necessary `_` on symbols with Win32 COFF object and Win32 PE executables. – Michael Petch Oct 02 '22 at 15:55