开发者

Limit the number of time a function can be used in a code base

Here is what I'm trying to do:

I have a legacy function that is used exactly 3 times in our code base. I want to get rid of this function but it will require sometime. Meanwhile, I would like to prevent other developers to use the fu开发者_如何学Cnction elsewhere. Is there a way to enforce this at compile time e.g. with an error?

Any ideas?

Update: I forgot to mention that my function resides in a namespace.


Don't put it in headers, to start with. Locally declare it in the .c file so that it's not as publically visible.

You could then do this as well:

public_header.h:

     #define my_function(arg1, arg2, ...) exit(128)

And in the .cpp file that actually needs to use it:

     #undef my_function
     int my_function(int arg1, char *arg2, ...);


For gcc you can use "deprecated" attribute.

int old_fn () __attribute__ ((deprecated));

This will emit warning every time function used somewhere.


As part of C++ no.

There are tricks, of course.

One such trick is to declare the function as locally as possible near the current point of use.

  • Simply declaring it at the top of the source file use it, right below the includes
  • Declaring it (and defining it) as static at the top of the source file that use it, better for visibility but implies duplication

It security by obscurity, not reknown for being that great, but I would deem it acceptable in this case (with a fat comment on top of the function).

Other solutions include #pragma warning in the header (not nice) or the deprecated attribute, but this will cause warnings for the current uses, this can be problematic (pollutes build output). And if people are not bothered with warnings for the current use, they won't bother for new warnings either, not a good habit to get into!

Now, there are other solutions.

You could simply write a hook that scan the sources files and count the number of occurrences.

grep -r "deprecated_func" include src | wc -l

This hook can be integrated either as part of the build process or as a pre-commit hook in your version system. Be sure to lower the number of allowed occurrences as soon as you get rid of one function.

Note: you can also use the deprecated attribute with a filter on the compiler output. But this does not count for -Werror.


Very interesting question! This got me thinking whether a combination of boost preprocessor's BOOST_PP_COUNTER and BOOST_STATIC_ASSERT (or C++0x's static_assert) would work. One big problem is every time I look into Boost.Preprocessor library, it makes my head spin :)

At the end, what I would like to write is BOOST_STATIC_ASSERT(BOOST_PP_COUNTER <= 3);

I don't have time to test my ideas right now, but hopefully this might lead to something. I won't be able to test my ideas until the weekend though...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜