Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a lambda have extern "C" linkage?

This seems to work on the platforms I have tried:

#include <iostream>

// extern "C" linkage
extern "C" void foo(void (*fn_ptr)(int));

namespace {
  struct bar {
    static void f(int);
  };
}

int main() {
  // Usually works on most platforms, not guaranteed though:
  foo(bar::f);

  // Probably equally bad or worse?
  foo([](int x) { std::cout << x << std::endl; });
}

but then again passing a static member function also worked on these platforms when it was not required to.

Is there a way to force a lambda to have suitable linkage to make this safe and portable? Or is it already?

like image 393
Flexo Avatar asked Sep 04 '11 19:09

Flexo


1 Answers

No. Lambdas are ultimately objects that have a function call operator. A captureless lambda can be converted into a function pointer of its appropriate type, but that function pointer will be a C++ function with C++ linkage.

like image 128
Nicol Bolas Avatar answered Sep 20 '22 19:09

Nicol Bolas