Clang/LLVM 9 and 10 SIGSEGV for inline static class members. Bug? - static

Using inline static class members in Clang gives me unexpected behaviour when the member is another class/struct:
https://godbolt.org/z/mbH6k7
// std=c++17
#include <iostream>
struct A {
double a = 42;
A() { std::cout << "A()" << std::endl; }
};
inline static A a{}; // No problem
namespace N {
inline static A a{}; // No problem
}
struct B {
B() { std::cout << "B()" << std::endl; }
inline static double d; // No problem with built-in types
A& a1 = N::a; // No problem
inline static A a2 = N::a; // No problem
inline static A a3{}; // <-- Problem here!
};
B b1;
inline static B b2;
int main() {
return 0;
}
Expected output, works in Clang 8.0.0, gcc, msvc:
A()
A()
A()
B()
B()
Actual output for Clang 9.0.0 and onwards: 139 (SIGSEGV).
Is this a bug, or what am I missing?

This sounds like a pretty cut-and-dry bug to me:
Per [class.static.data]
An
inline static data member may be defined in the class definition and may specify a brace-or-equal-initializer.
Your code conforms to this:
struct B {
// ...
inline static A a3{};
};

Related

Is there a way to avoid code duplication in multiple similar functions?

I am writing a family of functions which are to be embedded in a small micro-controller operating at very near real time, so every clock cycle counts. The functions are almost identical.
The only way that I can see to do this without duplicating vast chunks of code is to use the really ugly and frowned upon method of declaring the code in an include file which is then intentionally included multiple times.
The following works to demonstrate the concept:
// func.inc
// The absence of an include guard is intentional, as each time this file gets included
// the output will be different
void FUNC(int x)
{
/* SNIP - lots and lots of code that is duplicated between
variant A and B (and more) of the function
for ( ... 4096 )
{
for( lots more nested loops)
{
*/
// IMPORTANT - I do not want to call functions here as it is
// in a tight loop withconsecutive memory accesses of
// different sizes of strided sparse arrays
#ifdef A
printf("A %d\n", x);
#endif
#ifdef B
printf("B %d\n", x);
#endif
/*
}
}
*/
// main.c
#include <stdio.h>
#define FUNC func_A
#define A
#include "func.inc"
#undef A
#undef FUNC
#define FUNC func_B
#define B
#include "func.inc"
#undef B
#undef FUNC
#define FUNC func_AB
#define A
#define B
#include "func.inc"
int main()
{
func_A(10);
func_B(20);
func_AB(30);
printf("Done\n");
return 0;
}
My problem is that whilst this works, it looks hideous, and might be very confusing to someone else trying to understand it. Using a pointer to a function is too inefficient to be a viable option in this case.
Is there a solution that anyone can suggest without simply duplicating several slightly different versions of the same function?
It's not really clear what's pseudo code and real code here, but overall you should not use #define + #undef + #include for the purpose of different code generation. (You could do it with "X macros" though as a last resort. Not an ideal solution but better than this.)
The solution to " IMPORTANT - I do not want to call functions here" is to call functions.
Function inlining has been a thing for some 30 years and 20 years ago C got explicit language support for it. And nowadays compilers are much better than programmers to determine what to inline. I'll make an example with explicit inline just to demonstrate that calling functions does not affect performance, if done correctly.
With traditional C, you would do something like this:
#include <stdio.h>
static inline void SNIP (void)
{
puts(__func__);
}
static inline void A_stuff (int val)
{
printf("%s %d\n", __func__, val);
}
static inline void B_stuff (int val)
{
printf("%s %d\n", __func__, val);
}
typedef enum { A=1, B=2 } AB_t;
void func(AB_t ab, int val)
{
SNIP();
if(ab & A)
A_stuff(val);
if(ab & B)
B_stuff(val);
}
int main()
{
func(A, 10);
func(B, 20);
func(A|B, 30);
printf("Done\n");
return 0;
}
That's the sane solution. The only functions that are actually called in the generated machine code are func and the printing functions.
Alternatively, you could have done code generation with "X macros" too - these exist solely for the purpose of avoiding code repetition, at the expense of readability. Wouldn't really recommend it here, but I'll include an example for completeness:
#include <stdio.h>
#define FUNC_LIST \
X(A, 10) \
X(B, 20) \
X(AB, 30) \
static inline void SNIP (void)
{
puts(__func__);
}
static inline void A_stuff (int val)
{
printf("%s %d\n", __func__, val);
}
static inline void B_stuff (int val)
{
printf("%s %d\n", __func__, val);
}
static inline void AB_stuff (int val)
{
A_stuff(val);
B_stuff(val);
}
#define X(opt, val) void func_##opt (int x) { SNIP(); opt##_stuff(x); }
FUNC_LIST
#undef X
int main()
{
#define X(opt, val) func_##opt(val),
FUNC_LIST
#undef X
printf("Done\n");
return 0;
}
This is quite unreadable just like the original code, except "X macros" are something of a de facto standard for icky macro tricks to avoid code repetition.
This creates multiple functions just like a C++ template, so it isn't ideal for that reason as well.
Edit: The question was originally tagged with C++, hence the answer.
Make a template!
// func.hpp
#ifndef FUNCITON_HPP
#define FUNCITON_HPP
enum Specifier : int {
A = 1 << 0,
B = 1 << 1,
};
#include <cstdio>
template <auto sp>
void foo(int x)
{
/* SNIP - lots and lots of code that is duplicated between
variant A and B (and more) of the function
for ( ... 4096 )
{
for( lots more nested loops)
{
*/
// IMPORTANT - I do not want to call functions here as it is
// in a tight loop withconsecutive memory accesses of
// different sizes of strided sparse arrays
if constexpr (static_cast<bool>(sp & Specifier::A)) {
std::printf("A %d\n", x);
}
if constexpr (static_cast<bool>(sp & Specifier::B)) {
std::printf("B %d\n", x);
}
}
#endif //!FUNCITON_HPP
Then
// func.cpp
#include "func.hpp"
auto constexpr func_a = foo<Specifier::A>; // Could also use a #define
auto constexpr func_b = foo<Specifier::B>;
auto constexpr func_ab = foo<Specifier::A | Specifier::B>;
int main()
{
func_a(1);
func_b(1);
func_ab(1);
}

wrapper to make anonymous enums proper types

I have some typedef'd enums that are included from c-code, i.e. they are available in the form
typedef enum {FOO=3, BAR=5} my_enum;
and I would like use it in C++ code in a typesafe manner while leaving the enum names (FOO and BAR) and values (3 and 5) and their association unmodified.
Are there any best practices or patterns like template wrappers, that can be recommended to accomplish that, say in C++11 or higher?
In C++11 onwards you can declare these types as an enum class to get the type safety, but you must qualify usages with the name of the enum.
enum class my_enum {
FOO=3,
BAR=5
};
void my_func(my_enum e) {
}
int main() {
my_enum test_enum = my_enum::FOO;
my_func(test_enum);
}
If we changed the above definition of test_enum to my_enum test_enum = FOO; we'd get the error:
13:23: error: 'FOO' was not declared in this scope
It seems as if a
using
declaration works; at least the following compiles:
#include <iostream>
typedef enum{A=0, B=1, C=2} my_enum;
typedef enum{H=0, I=1, J=2} your_enum;
using namespace std;
using my_wrapper = my_enum;
using your_wrapper = your_enum;
int g(my_wrapper w)
{
return (int)w-10;
}
int g(your_wrapper w)
{
return (int)w+10;
}
int main() {
my_wrapper b=my_wrapper::B;
your_wrapper j=your_wrapper::J;
cout << g(b) << "\n";
cout << g(j) << "\n";
}

Linking C++ code to C in Borland C++ 3.1 compiler

Part of my FYP is to write code for a very old game(Wolfenstein-3D). It requires the use of the Borland C++ v3.1 compiler. This is the code I currently have but it's giving an error in the Borland compiler. Any ideas?
Error In Compiler:
Neuron.h
#ifdef __cplusplus // only actually define the class if this is C++
class Neuron {
public:
void foo();
int bar(int x, int y);
};
#else // C doesn't know about classes, just say it's a struct
typedef struct Neuron Neuron;
#endif
// access functions
#ifdef __cplusplus
#define EXPORT_C extern "C"
#else
#define EXPORT_C
#endif
EXPORT_C Neuron* NeuronNew(void);
EXPORT_C void NeuronDelete(Neuron* n);
EXPORT_C void NeuronFoo(Neuron* n);
EXPORT_C int NeuronBar(Neuron* n, int x, int y);
Neuron.cpp
#include "NEURON.h"
void Neuron::foo() {
}
int Neuron::bar(int x, int y) {
return x+y;
}
EXPORT_C Neuron* NeuronNew(void) {
return new Neuron();
}
EXPORT_C void NeuronDelete(Neuron* n) {
delete n;
}
EXPORT_C void NeuronFoo(Neuron* n) {
return n->foo();
}
EXPORT_C int NeuronBar(Neuron* n, int x, int y) {
return n->bar(x, y);
}
Usage in C source file
#include "NEURON.h"
...
void GameLoop (void)
{
...
Neuron* m = NeuronNew();
NeuronFoo(m);
NeuronDelete(m);
...
}
My assumption is that even though the compiler is a C++ compiler there's something 'new' in the C++ code that the compiler can't handle
The error message looks very much like the one you get from other compilers when they can't build the .cpp file for your class. It's not complaining about NeuronNew, but about _Neuron_new (note lowercase 'n' and extra underscore), so that's likely what Borland names the constructor/destructor?
Is it successfully compiling the .cpp and as C++? Is the file suffix mapping hooked up for those in the compiler? Have you added invalid code to the #ifdef __cplusplus line to verify that is ever defined, and not always defined (as 0 or 1)? Are you using the same case for all includes, file names and in the Makefile/project so they can be found?
Oh, have you tried doing:
typedef struct Neuron* NeuronPtr;
and then using NeuronPtr instead of Neuron* in the C wrapper? C++ Compiler shouldn't care (as long as you do a typedef class Neuron* NeuronPtr; in the __cplusplus part), but it means that it might no longer try to resolve the forward-declared struct in any C code.

Eigen's Map<> as a class member

I'm trying to have a class that contains array but have an interface to them through eigen.
class A {
public:
array<double,3> xa;
Map<Matrix<double,3,1>> x;
A() : x(xa.data(),xa.size()) {}
};
this doesn't work :
A a;
a.xa[0] = 0.12;
cout << a.x ;
I assume the problem is because Map<> doesn't have a default constructor. http://eigen.tuxfamily.org/dox/TutorialMapClass.html#TutorialMapPlacementNew
The example that you provide does work for me (Eigen 3.0.1 and GCC 4.6.1)
#include <Eigen/Core>
#include <array>
#include <iostream>
using namespace std;
using namespace Eigen;
class A {
public:
array<double,3> xa;
Map<Matrix<double,3,1>> x;
A() : x(xa.data(),xa.size()) {}
};
int main()
{
A a;
a.xa[0] = 0.12;
cout << a.x ;
}
when compiled with
g++ test.cpp -std=c++0x -o test -I/usr/include/eigen3
I get the following output when calling the resulting test executable:
[/tmp]% ./test
0.12
2.07717e-317
0%

Can I re-define a function or check if it exists?

I have a question about (re-)defining functions. My goal is to have a script where I can choose to define a function or not.
Like this:
void func(){}
int main(){
if (func)func();
}
AND without the function, just:
int main(){
if (func)func();
}
Anybody an idea?
You can do this in GCC using its weak function attribute extension:
void func() __attribute__((weak)); // weak declaration must always be present
int main() {
if (func) func();
// ...
}
// optional definition:
void func() { ... }
This works even if func() is defined in another .c file or a library.
Something like this, I think. Haven't used function pointers much, so I may have gotten the syntax slightly wrong.
void func()
{
#define FUNC_PRESENT
// code
}
void (*funcptr)();
#ifdef FUNC_PRESENT
funcptr = func;
#else
funcptr = NULL;
#endif
int main()
{
if (funcptr)
funcptr();
}
Use function pointers, set them dynamically based on runtime conditions, and check for null pointers or wrap them in methods that do that check for you.
Only option in C I can think of.
In C++ you could combine templates and DLLs to dynamically define at runtime.
Really the only way that you can "choose to define a function or not" is with C preprocessor directives. For example:
#ifdef some_name
void func() {
do_whatever();
}
#else
//the else part is optional
#endif
To set these "variables" you use #define some_name
The trouble is, all of this needs to be done at compile time (before that, actually) so it can't be done with an if statement like in your example. If you want an if statement to control your program flow, just use it and don't bother with trying to rename functions or using function pointers or something.
Introduction
I guess that you are trying to do this:
Two modules, a.o and b.o
b.o contains a definition for void foo()
a.o calls void foo() only if b.o is also linked into the final executable.
This could be useful for a "plugin" system.
Variation 1
You can simulate it using function pointers. I don't know enough C to write this in proper C code, but pseudocode looks like this:
a.h
extern collectionOfFuncPtrs_t list;
int addFuncPtr();
a.c
#include "a.h"
collectionOfFuncPtrs_t list;
int addFuncPtr(FuncPtr p) {
- add func ptr to list
- return 0
}
int main() {
- loop through list of function pointers
- call functions through them
}
b.c
#include "a.h"
void bar() { /* ... */ }
static int dummy = addFuncPtr(&bar);
c.c
#include "a.h"
void ayb() { /* ... */ }
static int dummy = addFuncPtr(&ayb);
Conclusion
Now, you can link in b.o and/or c.o as you wish, and int main() will only call bar() and/or ayb() if they exist.
Variation 2
Experiment with variations on this theme if it looks like it may be useful to you. In particular, if you have only a specific number of conditionally-defined functions, you could use a bunch of individual function pointers rather than some list:
a.h
extern fptr_t bar_ptr, ayb_ptr;
a.c
#include "a.h"
int main() {
if (bar_ptr)
bar_ptr();
if (ayb_ptr)
ayb_ptr();
}
b.c
#include "a.h"
void bar() { /* ... */ }
fptr_t bar_ptr = &bar;
b_dummy.c
#include "a.h"
fptr_t bar_ptr = 0;
c.c
#include "a.h"
void ayb() { /* ... */ }
fptr_t ayb_ptr = &ayb;
c_dummy.c
#include "a.h"
fptr_t ayb_ptr = 0;
Conclusion
Now either link b.o or b_dummy.o; and either link c.o or c_dummy.o.
I hope you get the general idea, anyway...!
Bootnote
This is a lot easier in C++ where you can write a module registration system very easily with std::maps and constructors.
In C? Only by using the preprocessor as stated in other answers.
C isn't a dynamic language like, say, Python.
The right way to do what I think you're asking about in C is to use function pointers. You can take the address of a function, assign it to a variable, test it for nil, etc. However, plain old C isn't a very dynamic language; you might be better off using a different language.
if you don't mind compiler specific extension, you can use __if_exists:
#include <iostream>
using namespace std;
// uncomment the following, and it'll still work
void maybeFunc(){ cout << "running maybe" << endl; }
int main(){
cout << "hi!" << endl;
__if_exists(maybeFunc)
cout << "maybe exists!" << endl;
maybeFunc();
}
}
this works in msvc by default, and in clang if you use the -fms-extensions flag.

Resources