c - c中#ifdefs的选择性预处理

标签 c c-preprocessor preprocessor-directive

我有很大的 .c 和 .h 文件,我必须从中只选择满足以下这些条件的预处理器指令

#if(VALUE==5) ||(VALUE==6)

预处理器指令的其余部分应该保持不变。我已经研究过 unifdefsunifdef 它们将允许我识别 #if#ifdef 但我不想选择所有 #if#ifdefs。是否有一个实用程序允许我给出,例如 VALUE==5 并只选择那些?

基本上我需要根据我的输入值选择预处理器指令。

最佳答案

尝试运行脚本,它将打印代码行和#if block 中的代码。 这只会静态扫描文件。你可以试一试。

# ./run.sh filename "String to search in if"
# example ./run.sh test.h "#if VALUE"

# Get the line number of Searching string locations
# store it in a file
awk "/$2/{ print NR }" $1 > temp_if

# to store total lines present inside the if contruct
totalLinesCount=0

# read one line at a time, that is go through one occurance of string at a time
while read matchLineNum
do
    printf "Match Found in line number $matchLineNum\n"
    #search for first occurance of #elif from the matched string.
    elifLineNum=$(tail -n +$(expr $matchLineNum + 1) $1 | awk "/#elif/{ print NR;exit }")
    if [ "$elifLineNum" == "" ]
    then
        # if not found set it to some high value
        elifLineNum=$(wc -c $1)
    fi
    elseLineNum=$(tail -n +$(expr $matchLineNum + 1) $1 | awk "/#else/{ print NR;exit }")
    if [ "$elseLineNum" == "" ]
    then
        elseLineNum=$(wc -c $1)
    fi
    endifLineNum=$(tail -n +$(expr $matchLineNum + 1) $1 | awk "/#endif/{ print NR;exit }")

    # check if #endif / #elif / #else occurs first
    if [ $endifLineNum -lt $elseLineNum -a $endifLineNum -lt $elifLineNum ]
    then
        # store the code count
        totalLinesCount=$(expr $totalLinesCount + $(expr $endifLineNum - 1))
        # store the code
        tail -n +$(expr $matchLineNum + 1) $1 | head -n $(expr $endifLineNum - 1) >> out

    elif [ $elseLineNum -lt $endifLineNum -a $elseLineNum -lt $elifLineNum ]
    then
        totalLinesCount=$(expr $totalLinesCount + $(expr $elseLineNum - 1))
        tail -n +$(expr $matchLineNum + 1) $1 | head -n $(expr $elseLineNum - 1) >> out

    elif [ $elifLineNum -lt $elseLineNum -a $elifLineNum -lt $endifLineNum ]
    then
        totalLinesCount=$(expr $totalLinesCount + $(expr $elifLineNum - 1))
        tail -n +$(expr $matchLineNum + 1) $1 | head -n $(expr $elifLineNum - 1) >> out

    else
        printf "\n Error \n"
    fi
done < temp_if
printf "\nTotal number of lines present inside the given condition is $totalLinesCount\n"
rm -f temp_if
printf '\nFinal Extracted Out\n'
cat out
rm -f out

关于c - c中#ifdefs的选择性预处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28323539/

相关文章:

Python 包 Cython 模块

C 在 32 位上定义 64 位

c - 取消引用数组名称

c - C语言中二进制数加一?

c - 在条件宏中定义变量会出现错误

c++ - 如何在宏 C++ 中使用 cout

c++ - 预处理器指令

c++ - 跨文件 #if 和 #endif - 应该合法吗?

Monodevelop 将 #if 和 #endif 之间的所有内容标记为 C# 文件中的注释

android - 如何在 android studio 中启用 neon 构建和调试 native 代码 (c)?