C++20's source_location compilation error when using NVCC 12.1


I have encountered an error while using source_location. Here is an simple example:

#include <iostream>
#include <source_location>

void printSourceLocation()
  auto location = std::source_location::current();

  std::cout << "FileName: " << location.file_name() << std::endl;

int main()

When compiling with GCC 11.3 or 12.1 I get this error:

$ nvcc -ccbin g++ -std=c++20 test.cu -o test
  test.cu(6): error: call to consteval function "std::source_location::current" did not produce a valid constant expression
    auto location = std::source_location::current();
  /usr/include/c++/12/source_location(59): note #2703-D: cannot call non-constexpr function "__builtin_source_location" (declared implicitly)
      current(__builtin_ret_type __p = __builtin_source_location()) noexcept

  1 error detected in the compilation of "test.cu".

Similarly when using Clang 15:

$ nvcc -ccbin clang++-15 -std=c++20 test.cu -o test
  /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/12/source_location(53): error: identifier "__builtin_source_location" is undefined
      using __builtin_ret_type = decltype(__builtin_source_location());

  1 error detected in the compilation of "test.cu".

Same story with NVC++. When not using NVCC, all compilers have no problem with this code.



1 Like

Submitted as NVIDIA bug #4173735.

Hi David,

I have a similar issue on Windows. But on Linux I use #include <experimental/source_location> instead and it compiles.

Ran into the same problem, was able to work around it at least for host code. Might also work for device code, but I didn’t look into that.

// workaround cuda compiler bug #4173735.
// https://forums.developer.nvidia.com/t/c-20s-source-location-compilation-error-when-using-nvcc-12-1/258026
#ifdef __CUDACC__
#pragma push_macro("__cpp_consteval")
#pragma push_macro("_NODISCARD")
#pragma push_macro("__builtin_LINE")

#define __cpp_consteval 201811L

    #undef _NODISCARD
    #define _NODISCARD

#define consteval constexpr

#include <source_location>

#undef consteval
#pragma pop_macro("__cpp_consteval")
#pragma pop_macro("_NODISCARD")
#include <source_location>

The source_location as implemented in MSVC uses the new C++20 consteval specifier to construct the current location at compile time but it doesn’t seem require it correctness, might just be a performance optimisation.