繁体   English   中英

检查是 C 结构中的成员

[英]Check is member in struct with C

我想访问结构中的成员,但检查该成员是否存在

#include <stdio.h>

int main()
{
    struct MyStruct { int a;};
    struct MyStruct temp ;
    temp.a=3;

    return 0;
}

有没有办法检查成员a是否在 struct m 中,如果不能使用#ifdef访问 b? 类似#ifdef MyStruct.a temp.a=3; #else temp.b=3; #endif #ifdef MyStruct.a temp.a=3; #else temp.b=3; #endif

在 C 中是不可能的。

如果您真的想检测结构的成员,通常的方法是首先编译使用该结构的示例程序,查看编译是否成功,并根据结果定义用于编译的编译器的预处理器宏rest 项目。 创建了各种构建系统来简化此类任务。 cmake的简短示例可能如下所示:

cat >mystruct.h <<EOF
struct MyStruct { 
    int a; // a? maybe not? no one knows.
};
EOF

cat >CMakeLists.txt <<EOF
cmake_minimum_required(VERSION 3.11)
project(test_include C)
# will try to compile a testing file
try_compile(mystruct_has_a "${CMAKE_BINARY_DIR}/temp" ${CMAKE_SOURCE_DIR}/test_mystruct_has_a.c)
add_executable(main main.c)
if(mystruct_has_a)
    target_compile_definitions(main PUBLIC MYSTRUCT_HAS_A)
endif()
EOF

cat >test_mystruct_has_a.c <<EOF
#include "mystruct.h"
int main() {
    struct MyStruct temp;
    temp.a = 3; // test - can we compile this?
}
EOF

cat >main.c <<EOF
#include <stdio.h>
#include "mystruct.h"
int main() {
    struct MyStruct temp ;
#if MYSTRUCT_HAS_A
    // it's ok to use `temp.a` here.
    temp.a = 3;
    printf("%d\n", temp.a);
#endif
}
EOF

可以从命令行编译:

cmake -S. -B_build && cmake --build _build --verbose

cmake将尝试编译文件test_mystruct_has_a.c 如果编译成功,那么宏MYSTRUCT_HAS_A将作为宏添加到编译器 arguments。 如果没有,则不会添加宏。 然后main.c将根据之前的结果使用或不使用该宏进行编译。 这种方式通常用于许多不同的项目中,主要是通过检测操作系统特定的东西来提供可移植性,例如sigactionsiginfo_tsched_param的成员。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM