stclib / STC

A modern, user friendly, generic, type-safe and fast C99 container library: String, Vector, Sorted and Unordered Map and Set, Deque, Forward List, Smart Pointers, Bitset and Random numbers.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Compilation Error with g++ due to Compound Literals Usage

bauom opened this issue · comments

Issue Description:

I've encountered a compilation issue when using the STC library, particularly in contexts where compound literals are utilized. The library documentation suggests compatibility with C and C++ code. However, compiling code that includes STC headers has revealed that the usage of compound literals leads to errors in certain C++ compilers. Notably, this code compiles successfully on compilers like clang++ 10.0.1 and Intel oneAPI 2024.0.2, but it fails on others, such as g++ 12.3.0 and nvc++ 23.1. This issue highlights a non-standard usage in C++ that affects compiler compatibility.

Example code:

#include "stc/cspan.h"

using_cspan3(myspan, int);

int main(void) {
    int arr[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24};

    myspan3 ms3 = cspan_md(arr, 2, 3, 4);
}

Error message:

stci/cspan.h:175:57: error: taking address of temporary array
              _cspan_shape2stride(layout, ((cstride_t []){__VA_ARGS__}), c_NUMARGS(__VA_ARGS__))}
                                          ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~
stci/cspan.h:169:5: note: in expansion of macro ‘cspan_md_layout’
     cspan_md_layout(c_ROWMAJOR, array, __VA_ARGS__)
     ^~~~~~~~~~~~~~~
tt.cpp:8:19: note: in expansion of macro ‘cspan_md’
     myspan3 ms3 = cspan_md(arr, 2, 3, 4);
                   ^~~~~~~~
Additional Context:

The use of compound literals in this context is not standard in C++, which leads to compilation errors with certain compilers. While some compilers, such as clang++ 10.0.1 and Intel oneAPI 2024.0.2, can successfully compile this code, others like g++ 12.3.0 and nvc++ 23.1 do not. This inconsistency suggests that the library's approach to using compound literals may not be fully portable across different C++ environments, particularly those that adhere strictly to the C++ standard.

Hi. Yes. cpan.h does not compile with C++, it should be marked. I think there is a way to fix it though by using c++ std::initializer_list, as is done in common.h.

In v50dev branch, cspan.h now compiles with c++.