Home >Backend Development >C++ >Do Distinct C Functions Always Have Distinct Addresses?

Do Distinct C Functions Always Have Distinct Addresses?

Susan Sarandon
Susan SarandonOriginal
2024-12-02 05:41:10382browse

Do Distinct C   Functions Always Have Distinct Addresses?

Do Distinct Functions Have Distinct Addresses?

In C , it's typically assumed that functions with different implementations have distinct addresses. However, this may not always hold true in certain scenarios.

Function Folding Optimization

Optimizing compilers may employ function folding to merge functions with identical implementations into a single entity. This can result in the functions sharing the same address.

While the C standard allows implementations to perform such optimizations, it remains unclear whether it's explicitly permitted for functions to share the same address.

As-if Rule and Observable Behavior

Under the as-if rule, compilers can optimize code if the observable behavior remains unchanged. Taking the address of a function is considered observable behavior.

Standard Interpretation

Defect report 1400 addresses this issue somewhat vaguely. It acknowledges that implementations may alias functions but leaves the exact interpretation of the standard open to debate.

Observations

There are concerns that function folding could break programs that rely on distinct addresses for functions. For instance, using function addresses as unique identifiers could be problematic if they're shared by multiple functions.

C11 Requirements

The C11 standard requires macros like SIG_DFL and SIG_ERR to generate distinct values that compare unequal to any declarable function. This suggests that the C standard prohibits functions from having the same address.

Recent Developments

A gcc developer clarified that MSVC's aggressive function folding violates the standard. Moreover, llvm-dev discussions emphasize that smarter linkers avoid combining functions unless one is used solely for calls and not for address observation.

Conclusion

Based on the available information, it's still unclear whether the current C standard explicitly prohibits or permits function folding optimizations that result in identical functions sharing the same address. The as-if rule gives compilers freedom to optimize, but observable behavior (taking function addresses) should remain unaffected. However, caution is advised, as function folding can potentially break code that relies on distinct function addresses.

The above is the detailed content of Do Distinct C Functions Always Have Distinct Addresses?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn