Skip to content

Instantly share code, notes, and snippets.

@andrep andrep/empty_struct_test.sh Secret
Created Dec 26, 2018

Embed
What would you like to do?
# Example & test for FTP-015
cat > empty_struct_test.c << EOF
#include <stdio.h>
// FIDL:
// struct Empty {};
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wzero-length-array"
typedef int FIDLEmptyStructInternal[0];
#pragma clang diagnostic pop
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++-compat"
#pragma clang diagnostic ignored "-Wextern-c-compat"
typedef struct {
FIDLEmptyStructInternal reserved;
} Empty;
#pragma clang diagnostic pop
int main() {
Empty e;
printf("sizeof(Empty): %zu\n", sizeof(e));
return 0;
}
EOF
clang empty_struct_test.c -Weverything -O0 -o empty_struct_test_c_O0 && ./empty_struct_test_c_O0
clang empty_struct_test.c -Weverything -O3 -o empty_struct_test_c_O3 && ./empty_struct_test_c_O3
cat > empty_struct_test.cc << EOF
#include <stdio.h>
// FIDL:
// struct Empty {};
extern "C" { // test including header files intended for C translation units
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wzero-length-array"
typedef int FIDLEmptyStructInternal[0];
#pragma clang diagnostic pop
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++-compat"
#pragma clang diagnostic ignored "-Wextern-c-compat"
typedef struct {
FIDLEmptyStructInternal reserved;
} CEmpty;
#pragma clang diagnostic pop
}
typedef struct {
private:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wzero-length-array"
#pragma clang diagnostic ignored "-Wunused-private-field"
int reserved[0];
#pragma clang diagnostic pop
public:
void Foo() {
// Can attach methods to an empty struct too, just like a normal struct.
printf("Foo called\n");
}
} CPPEmpty;
int main() {
CPPEmpty cpp_e;
CEmpty c_e;
printf("sizeof(CPPEmpty): %zu\n", sizeof(cpp_e));
cpp_e.Foo();
printf("sizeof(CEmpty): %zu\n", sizeof(c_e));
return 0;
}
EOF
clang++ empty_struct_test.cc -Weverything -O0 -o empty_struct_test_cpp_O0 -std=gnu++17 && ./empty_struct_test_cpp_O0
clang++ empty_struct_test.cc -Weverything -O3 -o empty_struct_test_cpp_O3 -std=gnu++17 && ./empty_struct_test_cpp_O3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.