26 Feb 2024
C++ code compiles with release build, fails with debug build (/D_DEBUG); MSVC obviously
Expectation: define _DEBUG (or switching between release and debug build) doesn’t change whether code is accepted; apparently Mircosoft has a different view...
// source code, x.cpp #include <cstdio> #include <string> static constexpr std::string s = “asdf”; int main() { printf(“%s\n”, s.c_str()); }Compile with debug:
cl /std:c++20 /D_DEBUG x.cpp Microsoft ® C/C++ Optimizing Compiler Version 19.39.33520 for x64 Copyright © Microsoft Corporation. All rights reserved. x.cpp x.cpp(4): error C2131: expression did not evaluate to a constant x.cpp(4): note: (sub-)object points to memory which was heap allocated during constant evaluationCompile as release:
cl /std:c++20 x.cpp Microsoft ® C/C++ Optimizing Compiler Version 19.39.33520 for x64 Copyright © Microsoft Corporation. All rights reserved. x.cpp Microsoft ® Incremental Linker Version 14.39.33520.0 Copyright © Microsoft Corporation. All rights reserved. /out:x.exe x.obj
Bonus: when the initializer string “asdf” is longer, e.g. “aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdf” also the release build fails (which is OK)
There's actually a very good and detailed technical explanation.
posted at: 10:00 | path: /programming | permanent link