Linker error: Multiple definition of a function

-3

I'm trying to write a program that includes .cpp and .h files.

Here is my code:

main.cpp:

#include "beep.h"
#include "movecursor.h"

beep.h:

#include <Windows.h>
#include <mmsystem.h>

DWORD WINAPI BeepSec(LPVOID parameters);

beep.cpp:

#include "beep.h"
#include "random.h"

DWORD WINAPI BeepSec(LPVOID parameters)
{

}

movecursor.h:

#include <Windows.h>
#include "beep.h"

DWORD WINAPI MoveCursor(LPVOID parameters);

movecursor.cpp:

#include "movecursor.h"
#include "random.h"

DWORD WINAPI MoveCursor(LPVOID parameters)
{

}

random.h:

#include <Windows.h>

int random() {
    HCRYPTPROV prov;
    if (prov == NULL)
        if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_SILENT | CRYPT_VERIFYCONTEXT))
    ExitProcess(1);

    int out;
    CryptGenRandom(prov, sizeof(out), (BYTE *)(&out));
    return out & 0x7fffffff;
}

But I got stuck with this linker error:

movecursor.cpp:(.text+0x0): multiple definition of 'random()' beep.cpp:(.text+0x0): first defined here

c++
winapi
linker
asked on Stack Overflow Nov 3, 2019 by MARSHMALLOW • edited May 12, 2020 by yivi

1 Answer

2

Put the definition of random() in a .cpp source file.

Use include guards in your .h header files:

#ifndef RANDOM_H
#define RANDOM_H
extern int random();
...
...
#endif
answered on Stack Overflow Nov 3, 2019 by suspectus • edited Apr 4, 2020 by Peter Mortensen

User contributions licensed under CC BY-SA 3.0