The TARGET_IPHONE_SIMULATOR macro does not work in the C++ source I added to the project. Though it should be noted that the code runs if I simply change out the macro with a 1 or a 0.
So here's the setup. I've been converting the files from :
https://code.google.com/p/ld48jovoc/source/browse/util/tweakval/?r=13 to work with the iOS application I'm making in XCode.
Everything is pretty much the same except for the header.
#ifndef TWEAKVAL_H
#define TWEAKVAL_H
#ifdef __cplusplus
extern "C" {
#endif
#include <sys/types.h>
// Do only in debug builds on simulator, this does NOT work on iOS device
#if TARGET_IPHONE_SIMULATOR // replace with 1 or zero to make it work
# define TV_USE_TWEAKVAL 1
#else
# define TV_USE_TWEAKVAL 0
#endif
//
// See the thread referenced above for idea of how to implement
// this without the __COUNTER__ macro.
// If we are in a build modethat wants tweakval, and the compiler
// supports it, use it
#if TV_USE_TWEAKVAL
# define _TV(Val) _TweakValue( __FILE__, __COUNTER__, Val )
//float _TweakValue( const char *file, size_t counter, float origVal );
int _TweakValue( const char *file, size_t counter, int origVal );
void ReloadChangedTweakableValues();
#else
// don't use it
# define _TV(Val) Val
# define ReloadChangedTweakableValues()
#endif
#ifdef __cplusplus
} // extern "C"
#endif
#endif
the cpp file is nearly identical except the whole thing is wrapped in #if TV_USE_TWEAKVAL.
Now I could set this macro manually, via code or in the build settings but I'd prefer to get this thing to automatically enable/disable via detecting the preprocessor command. My guess is that macro is not getting detected when it links the tweakval source code and I don't know what build settings I need to change to fix this issue.
Thanks.
TARGET_IPHONE_SIMULATOR comes from TargetConditionals.h. You need to #include that file. Presumably your other code gets it indirectly via some other path like Cocoa/Cocoa.h.
Related
I have a set of functions written in C that I need to be able to call from another project written in C++. The C code is essentially some functions that do some calculations on a large data set. I didn't write them - all I want to do is allow my C++ project to be able to call those functions. My solution was to create a DLL for the C code and link it to my C++ project.
In order to make the DLL, I structured myCproj.h (the header in the C project, not C++ project) like so:
#ifdef __cplusplus
extern "C" {
#endif
struct __declspec(dllexport) neededStruct {
int a;
//I need to be able to initialize this struct in my C++ project.
}
__declspec(dllexport) void neededFunc( struct neededStruct *input ) {}
//I need to be able to call this function from my C++ project and feed
//it my local instance of neededStruct.
#ifdef __cplusplus
}
#endif
The src file, myCproj.c, was not changed at all. The function definitions do not have __declspec(dllexport)in front of them, nor is extern "C" inserted anywhere. The code compiles without error and produces myCproj.dll and myCproj.lib.
I then tell my C++ project in VS where to find myCproj.lib and myCproj.h accordingly and copy the DLL over to the directory where my C++ executable lives. To use the DLL, I gave myCPPproj.cpp the following addition:
#define DLLImport __declspec(dllimport)
struct DLLImport neededStruct input;
input.a = 0;
extern "C" DLLImport void neededFunc( &input );
However, I get error EO335 'linkage specification is not allowed' on that last line. What am I doing wrong?
It is preferable to use the same header for both the library and using code.
As mentioned, it is usually done by a conditional define, like the following:
MyLibrary.h:
#if defined(MYLIBRARY_API)
#define MYLIBRARY_EXPORTS __declspec(dllexport)
#else
#define MYLIBRARY_EXPORTS __declspec(dllimport)
#endif
#if defined(__cplusplus)
extern "C" {
#endif
MYLIBRARY_API bool MyLibFunc();
#if defined(__cplusplus)
#endif
MyLibrary.c:
#include "MyLibrary.h"
void MyLibFunc()
{
....
}
App.cpp:
#include <MyLibrary.h>
int main()
{
MyLibFunc();
}
The symbol MYLIBRARY_API will be defined for the library project (usually as a /D on the compiler command line). And if you use visual studio that is pretty much exactly what you get when creating a dll project with exports.
I found some lines of code, those are dimmed in my preprocessor block of source code in C. My compiler, MS Visual Studio, naming it "inactive preprocessor block". What does this mean, will my compile do not consider these lines of code,
and how to make it active block?
An inactive preprocessor block is a block of code that is deactivated because of a preprocessor directive. The simplest example is:
#if 0
//everytyhing here is inactive and will be ignored during compilation
#endif
A more common example would be
#ifdef SOME_VAR
// code
#else
// other code
#endif
In this case either the first or the second block of code will be inactive depending on whether SOME_VAR is defined.
Please check this hypothetical example created to elaborate your question.
#include <iostream>
#include <windef.h>
#define _WIN32
int add(int n1, int n2){return n1 + n2;}
LONGLONG add(LONGLONG n1, LONGLONG n2){return n1 + n2;}
int _tmain(int argc, _TCHAR* argv[])
{
#ifdef _WIN32
int val = add(10, 12);
#else
LONGLONG = add(100L, 120L);//Inactive code
#endif // _WIN32
return 0;
}
You can see as _WIN32 is defined the code in #else pre-processor directive is disabled and would not be compiled. You can undefine _WIN32 to see reverse in action. See the screen shot of MS Visual Studio attached. The line in red is disabled code.
Hope this would help.
The preprocessor is one the earliest stages of a programs translation. It can modify the source of the program before the compilation stage begins. That way you can configure the source to build differently, depending on various constraints.
Uses of preprocessor condition blocks include:
Completely commenting out code:
#if 0
// The code here is never compiled. It's "commented" away
#endif
Provide different implementations based on various constraints, like platfrom
#if defined(WIN32)
//Implement widget with Win32Api
#elif defined(MOTIF)
// Implement widget with Motif framework
#else
#error "Unknown platform"
#endif
Have a macro like assert behave in different ways.
Make sure a useful abstraction is defined appropriately:
#if PLATFORM_A
typedef long int32_t;
#elif PLATFORM_B
typedef int int32_t;
My question is quite straight forward. I just intended to know that is the #define directive in C++ controllable over the different project files? Elaborately, I have a header file and a cpp file for one project. The codes of the files are as follows:
MyHeader.h
#ifndef __MY_HEADER_H__
#include <cstring>
using namespace std;
#ifdef _HEADER_EXPORT_
#define HEADER_API __declspec(dllexport)
#else
#define HEADER_API __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
class HEADER_API MyHeader
{
public:
MyHeader();
~MyHeader();
#ifdef _HEADER_DISPLAY_
void __cdecl ParseHeader();
#elif defined (_HEADER_RETURN_)
string __cdecl ParseHeader();
#endif
};
#ifdef __cplusplus
}
#endif
#define __MY_HEADER_H__
#endif
MyHeader.cpp
#ifndef __MY_HEADER_H__
#include "MyHeader.h"
#endif
MyHeader::MyHeader() { }
MyHeader::~MyHeader() { }
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _HEADER_DISPLAY_
HEADER_API void __cdecl MyHeader::ParseHeader()
{
fputs(string("Displaying...").c_str(), stdout);
}
#elif defined (_HEADER_RETURN_)
HEADER_API string __cdecl MyHeader::ParseHeader()
{
string retVal("Returning...");
return retVal;
}
#endif
#ifdef __cplusplus
}
#endif
In another project HeaderImpl.cpp file has been implemented with the following code.
HeaderImpl.cpp
#include "stdafx.h"
#define _HEADER_DISPLAY_ // To display the message
// #define _HEADER_RETURN_ // To return the message as string
#include "MyHeader.h"
int main(int argc, char* argv[])
{
MyHeader header;
MyHeader.ParseHeader(); // To display the message or to return the string
return 0;
}
Now, I wanted to know that how can I use the #define directive in my HeaderImpl.cpp file to control the ParseHeader method for MyHeader.cpp file? As it has been noted that MyHeader.h file doing exactly what I need for; i.e. controlling the ParseHeader method upon declaring the #define directive, accordingly.
You can't. Each C++ source file is compiled independently, and settings in one cannot affect another. You'll have to do this on project level.
One way to do that would be to set up different project (and solution) configurations for different values of this macro. Instead of just the usual Debug and Release, you could add Debug-Display, Debug-Return etc. You can then define the macros in the project settings for each configuration. This will make sure you link the correctly built version of your library.
As a side note, you're using illegal names in your code. A name which contains double underscores, or starts with an underscore followed by an uppercase letter, is reserved for the compiler & standard library. User code is not allowed to use such names for its own purposes.
You usually can provide #defines for all of your compilation units on the command line of the compiler. IIRC for Visual studio that would be something like /D_HEADER_DISPLAY_ or /D_HEADER_RETURN_
Your project must be using something like this already for the _HEADER_EXPORT_ define.
There is no way for a preprocessor definition in one translation unit to remotely affect a different translation unit.
Most, if not all, compilers accept them as parameters for the compilation, though (and the flag is usually -D, or /D for VC++).
In Visual Studio, you can set project-wide preprocessor definitions in the project settings, under
Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions
I can do this in Visual C++ 2008 with Release (NDEBUG) setting:
debug.h
#ifdef _DEBUG
void debug_printf(const char* format, ...);
#else
#define debug_printf(format, v) __noop
#endif
debug.cpp
#include "stdafx.h" //#include "debug.h" is inside it
void debug_printf(const char* format, ...) {
//so much work here
}
but not anymore in Visual C++ 2013, I will get compile error in debug.cpp file. It seems I have to change the defining strategy in debug.h. But I wonder is there compiler setting to reenable again the old way?
Use a macro in the first case too, and let it call the actual function (which is named something different from the macro).
And in the second case, just have an empty macro body.
Use variadic macros.
Something like
#ifdef _DEBUG
# define debug_printf(fmt, ...) real_debug_printf(fmt, __VA_ARGS__)
#else
# define debug_printf(fmt, ...)
#endif
When _DEBUG is not defined, then the macro debug_printf is replaced by nothing (or rather, an empty line).
I have encountered the #define pre-processor directive before while learning C, and then also encountered it in some code I read. But apart from using it to definite substitutions for constants and to define macros, I've not really understook the special case where it is used without a "body" or token-string.
Take for example this line:
#define OCSTR(X)
Just like that! What could be the use of this or better, when is this use of #define necessary?
This is used in two cases. The first and most frequent involves
conditional compilation:
#ifndef XYZ
#define XYZ
// ...
#endif
You've surely used this yourself for include guards, but it can also be
used for things like system dependencies:
#ifdef WIN32
// Windows specific code here...
#endif
(In this case, WIN32 is more likely defined on the command line, but it
could also be defined in a "config.hpp" file.) This would normally
only involve object-like macros (without an argument list or
parentheses).
The second would be a result of conditional compilation. Something
like:
#ifdef DEBUG
#define TEST(X) text(X)
#else
#define TEST(X)
#endif
That allows writing things like:
TEST(X);
which will call the function if DEBUG is defined, and do nothing if it
isn't.
Such macro usually appears in pair and inside conditional #ifdef as:
#ifdef _DEBUG
#define OCSTR(X)
#else
#define OCSTR(X) SOME_TOKENS_HERE
#endif
Another example,
#ifdef __cplusplus
#define NAMESPACE_BEGIN(X) namespace X {
#define NAMESPACE_END }
#else
#define NAMESPACE_BEGIN(X)
#define NAMESPACE_END
#endif
One odd case that I recently dug up to answer a question turned out to be simply commentary in nature. The code in question looked like:
void CLASS functionName(){
//
//
//
}
I discovered it was just an empty #define, which the author had chosen to document that the function accessed global variables in the project:
C++ syntax: void CLASS functionName()?
So not really that different from if it said /* CLASS */, except not allowing typos like /* CLAAS */...some other small benefits perhaps (?)
I agree with every answer, but I'd like to point out a small trivial thing.
Being a C purist I've grown up with the assertion that EACH AND EVERY #define should be an expression, so, even if it's common practice using:
#define WHATEVER
and test it with
#ifdef WHATEVER
I think it's always better writing:
#define WHATEVER (1)
also #debug macros shall be expressions:
#define DEBUG (xxx) (whatever you want for debugging, value)
In this way, you are completely safe from misuse of #macros and prevents nasty problems (especially in a 10 million line C project)
This can be used when you may want to silent some function. For example in debug mode you want to print some debug statements and in production code you want to omit them:
#ifdef DEBUG
#define PRINT(X) printf("%s", X)
#else
#define PRINT(X) // <----- silently removed
#endif
Usage:
void foo ()
{
PRINT("foo() starts\n");
...
}
#define macros are simply replaced, literally, by their replacement text during preprocessing. If there is no replacement text, then ... they're replaced by nothing! So this source code:
#define FOO(x)
print(FOO(hello world));
will be preprocessed into just this:
print();
This can be useful to get rid of things you don't want, like, say, assert(). It's mainly useful in conditional situations, where under some conditions there's a non-empty body, though.
As you can see in the above responses, it can be useful when debugging your code.
#ifdef DEBUG
#define debug(msg) fputs(__FILE__ ":" (__LINE__) " - " msg, stderr)
#else
#define debug(msg)
#endif
So, when you are debugging, the function will print the line number and file name so you know if there is an error. And if you are not debugging, it will just produce no output
There are many uses for such a thing.
For example, one is for the macro to have different behavior in different builds. For example, if you want debug messages, you could have something like this:
#ifdef _DEBUG
#define DEBUG_LOG(X, ...) however_you_want_to_print_it
#else
#define DEBUG_LOG(X, ...) // nothing
#endif
Another use could be to customize your header file based on your system. This is from my mesa-implemented OpenGL header in linux:
#if !defined(OPENSTEP) && (defined(__WIN32__) && !defined(__CYGWIN__))
# if defined(__MINGW32__) && defined(GL_NO_STDCALL) || defined(UNDER_CE) /* The generated DLLs by MingW with STDCALL are not compatible with the ones done by Microsoft's compilers */
# define GLAPIENTRY
# else
# define GLAPIENTRY __stdcall
# endif
#elif defined(__CYGWIN__) && defined(USE_OPENGL32) /* use native windows opengl32 */
# define GLAPIENTRY __stdcall
#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 303
# define GLAPIENTRY
#endif /* WIN32 && !CYGWIN */
#ifndef GLAPIENTRY
#define GLAPIENTRY
#endif
And used in header declarations like:
GLAPI void GLAPIENTRY glClearIndex( GLfloat c );
GLAPI void GLAPIENTRY glClearColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha );
GLAPI void GLAPIENTRY glClear( GLbitfield mask );
...
(I removed the part for GLAPI)
So you get the picture, a macro that is used in some cases and not used in other cases could be defined to something on those cases and nothing to those other cases.
Other cases could be as follows:
If the macro doesn't take parameters, it could be just to declare some case. A famous example is to guard header files. Another example would be something like this
#define USING_SOME_LIB
and later could be used like this:
#ifdef USING_SOME_LIB
...
#else
...
#endif
Could be that the macro was used at some stage to do something (for example log), but then on release the owner decided the log is not useful anymore and simply removed the contents of the macro so it becomes empty. This is not recommended though, use the method I mentioned in the very beginning of the answer.
Finally, it could be there just for more explanation, for example you can say
#define DONT_CALL_IF_LIB_NOT_INITIALIZED
and you write functions like:
void init(void);
void do_something(int x) DONT_CALL_IF_LIB_NOT_INITIALIZED;
Although this last case is a bit absurd, but it would make sense in such a case:
#define IN
#define OUT
void function(IN char *a, OUT char *b);