tags:

views:

332

answers:

4

I was wanting to use a constant of some kind for the application ID (so I can use it in printf).

I had this:

#define _APPID_ "Hello World!"

And then the simple printf, calling it into %s (string). It put this out:

simple.cpp:32: error: cannot convert ‘_IO_FILE*’ to ‘const char*’ for argument ‘1’ to ‘int printf(const char*, ...)’

What would I use to define the application ID to use in printf? I tried:

static const char _APPID_[] = "Hello World"`

but it didn't work, same error I think.

+2  A: 

I'm not sure I understand exactly what you tried... but this works:

#include <stdio.h>

#define _APPID_ "Hello world"

int main()
{
    printf("The app id is " _APPID_ "\n");
    /* Output: The app id is Hello world */
    return 0;
}

When presented with two constant strings back to back (i.e. "hello " "world"), the compiler treats them as a single concatenated constant string ("hello world").

That means that in the case of trying to printf a compile-time constant string, you don't need to use printf("%s", _APPID_) (although that should still work).

Mark Rushakoff
Actually, do use `printf("%s", APP_ID)`. If you ever rename your app to "200% productivity booster", calling `printf(APP_ID)` wouldn't work too well.
MSalters
+2  A: 

According to the error message, the problem is most likely not caused by the string constant, but by incorrect parameters given to printf().

If you want to print to a file, you should use fprintf(), not printf(). If you want to print to the screen, use printf(), but don't give a file handle as its first parameter.

sth
A: 

In source.h

#ifndef _SOURCE_H
#define SOURCE_H
#ifdef APP_ID
#define WHOAMI printf("%s\n", APP_ID);
#endif
#endif

In your program:

#define APP_ID __FILE__
#include "source.h"
int main()
{
    WHOAMI
    return 0;
}

the reason for this is to have a stadnard include file - source.h. __FILE__ inside a header file returns the name of the header file, so the APP_ID definition is constrained to live in the C file.

If you don't define APP_ID the code won't compile.

jim mcnamara
A: 

_APPID_ is a name that's reserved for the implementation. It matches the pattern ^_[A-Z].*

Rename it to e.g. APP_ID.

MSalters