0

I'm kinda confused when having the PlaySound function in my code. I did a double check the syntax and pretty sure I used the necessary library.

I'm using GCC version 5.1.0 and I had my WAV file in the same directory. Also, here is my code and the error in the console:

#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <mmsystem.h>
#pragma comment(lib,"winmm.lib")

int main(){
 for(;;){
  PlaySound("C:\\Users\\ACER\\Documents\\Tick.WAV", NULL, SND_ASYNC | SND_FILENAME);
  Sleep(1000);
 }
return 0;
}

Error in console:
C:\Users\ACER\AppData\Local\Temp\ccokPOhD.o:test1.cpp:(.text+0x2e): unidentified reference to '_imp__PlaySoundA@12'
collect2.exe: error: ld returned 1 exit status

If I'm doing anything wrong or missing something, please let me know. Thank you.

Jin
  • 1
  • 1
  • There are just a few reason why you can get an undefined reference. Most of the time, there is a file that is not compiled, or the function implementation has a different signature from the declaration, or you don't link to a library. Without any other details (you don't show the implementation of `PlaySound`) The only solution I can offer is already in the dupe question. Let me know if you have other specific problem not answered there I could help you with. – Guillaume Racicot Aug 11 '22 at 03:55
  • I looks like the function was not declared as `extern "C"`. The docs say to just include `windows.h`. What happens if you remove the `#include `? – jkb Aug 11 '22 at 03:56
  • 1
    This builds as-is in VS2022. Sorry, I don't have gcc installed on my Windows box. Nonetheless, it appears to be trying to link against a C++ mangled name. I'm not convinced that gcc supports `#pragma comment`, so you probably have to specify the library on the compile/link command line. – jkb Aug 11 '22 at 04:06
  • @jkb It still the same 'unidentified reference' line – Jin Aug 11 '22 at 06:34
  • @jkb: No, it does NOT appear to link against a C++ mangled name. That's a C/Windows mangled name. It's a common mistake for people coming from Linux, but Windows often mangles C names too. E.g. the `@12` comes from the 12 bytes needed for the arguments. – MSalters Aug 11 '22 at 09:45
  • The problem is indeed GCC"s support for `#pragma comment (lib, )`. A `#pragma` is implementation-specific, and GCC chooses to ignore it. MSVC invented this particular `#pragma`, so it compiles there. – MSalters Aug 11 '22 at 09:49
  • @Jin if GCC ignore pragma comment, you need to properly link to the library using either command line flags or your buildsystem configuration – Guillaume Racicot Aug 11 '22 at 13:37

0 Answers0