-2

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

yivi
  • 42,438
  • 18
  • 116
  • 138
MARSHMALLOW
  • 1,315
  • 2
  • 12
  • 24
  • 1
    `int random()` - you implement it in `random.h` and then include it to `movecursor.cpp` and `beep.cpp` - so in both this files the same `int random()` exist. you need create `random.cpp` for example and implement `int random()` here. – RbMm Nov 03 '19 at 11:38
  • But using random.h will result in a compile error? – Peter Mortensen Apr 04 '20 at 04:53
  • 3
    Does this answer your question? [multiple definition: error at link time](https://stackoverflow.com/questions/32504570/multiple-definition-error-at-link-time). Also same problem: [multiple definition linker error after adding a function to a previously linking file](https://stackoverflow.com/questions/3136616/multiple-definition-linker-error-after-adding-a-function-to-a-previously-linking) – BDL May 12 '20 at 11:55
  • @BDL No, not at all. – MARSHMALLOW May 12 '20 at 13:30
  • 2
    You have multiple definition of your `random` function, since multiple files include that header, which causes the linker to fail. Either put your random function in a separate cpp file, or mark it inline. Both links provided by BDL explain this. – ChrisMM May 12 '20 at 14:52

1 Answers1

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
suspectus
  • 16,548
  • 8
  • 49
  • 57