在现有C库中重新定义宏

时间:2015-10-15 15:25:14

标签: c macros c-preprocessor

假设我有一些代码如下:

L - A common library (source) (via svn:extern)
X - My project
Y - A static library (source) (via svn:extern) compiled with X and depends on L

L内部,XY

中的代码中广泛存在一个宏
#define FOO() printf("Hello World\n")

我想将其更改为

#define FOO() printf("===> Hello World <===")

现在,我知道在我的代码X中,我可以这样做:

#ifdef FOO
    #undef FOO
    #define FOO() printf("===> Hello World <===")
#endif

适用于X,但对Y中的任何代码和编译都没有帮助。我可以在本地修改YL的代码,但之后我无法检查我的修改,因为它可能会破坏其他项目对FOO所做的期望。

是否可以通过命令行修改宏,与-D同样徒劳无功?如果是这样,那么我可以更改Makefile中的行为,任何签出X的人都可以访问改进的FOO。使用-D的问题在于它将在 XY #include L's宏之前定义宏函数,这将导致宏重新定义警告(后来不是我想要的宏)。

3 个答案:

答案 0 :(得分:3)

假设L使用标头防护, 你可以做点什么

l_improved.h

中的

#ifndef L_IMPROVED_H
#define L_IMPROVED_H

#include "L.h"

#ifdef FOO
    #undef FOO
    #define FOO() printf("===> Hello World <===");
#endif

#endif

然后添加:

-include l_improved.h

在你的gcc编译器标志中。

来自gcc Preprocessor-Options

-include file:处理文件,好像#include&#34; file&#34;出现在主要源文件的第一行。

如果使用其他编译器,则标志可能不同。

答案 1 :(得分:1)

我认为最好的整体修复方法是修改#ifndef FOO #define FOO() printf("Hello World\n") #endif 内的定义,如下所示:

FOO

您可以在不破坏任何其他人的代码的情况下签入此更改,然后很容易从命令行或在makefile中覆盖<?php error_reporting(~E_WARNING); if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created \n"; if( !socket_bind($sock, "0.0.0.0" , 9999) ) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not bind socket : [$errorcode] $errormsg \n"); } echo "Socket bind OK \n"; while(1) { echo "Waiting for data ... \n"; $r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port); echo "$remote_ip : $remote_port -- " . $buf; socket_sendto($sock, "OK " . $buf , 100 , 0 , $remote_ip , $remote_port); } socket_close($sock); ?> 的定义。

答案 2 :(得分:0)

除了在构建Y文件之前操作make文件(比如附加您编写的代码)之外,我还没有办法做到这一点。

这非常简单,可以使用Y_modified.cpp命令将文件转换为Y.cpp,然后使所有构建使用修改后的版本。这样您就可以将它们视为半构建文件,并获得增量构建的所有好处。

包含L.h的单个L将转换为一个翻译单元,您可以在预处理器运行后真正注入任何内容。