If I call srand in my main function, would it also affect results in my functions in other translation units?
If I call srand in my main function, would it also affect results in my functions in other translation units?
Some small information from the source code of glibc.
srand is a weak alias for __srandom. (Source).
__srandom calls __srandom_r (Source).
__srandom_r is just updating the struct random_data passed to it, based on the seed.
(Source)
rand(void) is just calling __random. (Source).
__random calls __random_r, passing the same structure, that was passed to __srandom_r. (Source).
__random_r then generates a random value from the passed struct. (Source).
So, to put it in a nutshell, a call to srand in your main-function will affect the random numbers in every other function, while your program runs, as the state is shared between all functions.
C translation units bound the scope for some identifiers that are declared within, but not for any actual functions or objects belonging to a program. Thus, program state cannot be TU-specific, in the sense that it varies for different TUs.
Specifically, then, in any particular thread of a program exercising only defined behaviors, the random number seed set via srand() cannot appear differently to code in one TU than it would do at the same time to code in a different TU.