1

(I'm on Windows.)

I'm testing a DLL I have compiled (libsox) with a C program which looks this way:

#include <stdio.h>
#include "sox.h"

int main(void) {
    char const * versionText = sox_version();
    printf(versionText);
    return 0;
}

The function that is defined in the DLL has the following prototype in sox.h (something of this contains cdecl):

LSX_RETURN_VALID_Z LSX_RETURN_PURE
char const *
LSX_API
sox_version(void);

Here's the problem: When I try to build the file with gcc -lsox -o test.exe test.c I get the following error:

C:\DOKUME~1\ADMINI~1\LOKALE~1\Temp\ccSS2h2z.o:test.c:(.text+0xf): undefined reference to `sox_version'
collect2: ld returned 1 exit status

A word to -lsox: I have the library file "libsox.dll.a" in MinGW's lib folder. If I write -lsoxnonsense, then it says there is no library. That means in the shown case it finds the library. So why doesn't it want to create a link.

rynd
  • 1,865
  • 5
  • 22
  • 24
  • Did you build that library with the same compiler? Sometimes a `_` gets prepended to symbol names. – Carl Norum Apr 18 '12 at 00:00
  • Yes, it was the same compiler. I think the object file and the .a file contained both _sox_version. – rynd Apr 18 '12 at 00:15

1 Answers1

3
gcc -lsox -o test.exe test.c

You have to put your source file first:

gcc test.c -lsox -o test.exe

It is because the linker goes through the input files in order, finding undefined references and satisfying references that it saw before. So in your command line, it reads libsox.a (or something like that), finds undefined references (there would be none). Then, it goes to your test.c, finds undefined references in there, but there are no further libraries to satisfy them.

See this answer for more info.

Community
  • 1
  • 1
jpalecek
  • 47,058
  • 7
  • 102
  • 144
  • Thank you, this did the trick! I found it really strange at first, because the help says "Usage: gcc [options] file...". But I think you mean the library file is an input file, too. Therefore "gcc -o test.exe test.c -lsox" also works and gcc is inconsistent with it's stated usage. – rynd Apr 18 '12 at 00:26