Search code examples
c++crandom

_CRT_RAND_S: How does it working in Windows C/C++?


I wrote code like this:

#include <iostream>
#define _CRT_RAND_S  // may this line cause problem
#include <stdlib.h>


int main(void)
{
    unsigned int r;
    rand_s(&r);

    // ...

    return 0;
}

and compiler said, cannot find rand_s(). Then I switched line 1 and 2, it works.

#define _CRT_RAND_S
#include <iostream>
#include <stdlib.h>
// ...

Question is,

  1. Why do I have to define _CRT_RAND_S at the top of code?
  2. Does <iostream> depends on _CRT_RAND_S? It seems not but...

I tried this in Windows x64, Visual Studio 2022. Thanks.


Solution

    1. Why do I have to define _CRT_RAND_S at the top of code?

    According to the documentation:

    The _CRT_RAND_S constant must be defined before the stdlib.h header for the rand_s function is included, ...

    And to make sure that happens, you must define it before including any other header files, because header files (even the standard header files) are allowed to include other header files.

    1. Does <iostream> depends on _CRT_RAND_S? It seems not but...

    Most probably not, but iostream most probably includes stdlib.h, either directly or indirectly.