I am new to C/C++. Wanted to know why we cannot declare 'extern C' for C++ macro's similar to methods/functions...which will allow macro's defined in C++ file to be accessed in .c files.
Thanks in Advance
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.
Sign up to join this communityMacros in both C and C++ are a text replacement mechanism. Because of that, you can't define a macro in one source file and use it in a different source file.
What you can do is define a macro in a header file and include that header in both C and C++ source files where you want to use that macro. Such a header would need to contain only code that comes from the common subset of C and C++ so it will be acceptable in both languages.
#define f_x(x) cout << (x) << endl;
in a header file that's included from a plain C source code file? As long as you don't f_x("whatever");
or somesuch in your C source code, you should be fine, because the expanded form never occurs in the post-preprocessed (ugh!) C code. (#include <iostream>
or the ilk inside that header file may be trickier :))
f_x
macro.
Apr 22, 2013 at 14:35
__cplusplus
is not defined. But really, don't use macros in C++.
Generally, you should not use macros in C++ at all. The main reason is that macros do not respect scope. They simply drop a chunk of code in the middle of your source file. This can cause all manner of bugs, which will be very hard to find, because you would have to do this textural insertion in your head.
In C++, if the cost of a function call is your performance bottleneck, then you should use inline
functions, which do respect scope, instead of macros.
If you need to share code between C++ and C, then you probably should write a proper C function and declare that as extern "C"
. If you need to be able to call C++ code from C, then you should write a very thin C wrapper function around it.
IMHO, the simplest thing to do is to just use C++. The only reason to use C would be if you are working on an embedded platform, which doesn't have a C++ compiler.
#ifdef __cplusplus
. What possible reason is there to use macros? See "Effective C++" by Scott Meyers.
.def
and .inc
files in Clang sources. It is quite an idiomatic way of using preprocessor in C++.