-1

I am getting error while executing below code .Can anyone explain what mistake i am doing ?

#include <iostream>
using namespace std;
#define one 1
#ifdef one
    printf("one id defined");
#endif
void func1(); 
void __attribute__((constructor)) func1(); 
void func1() 
{ 
        printf("before"); 
} 
int main() 
{ 
    cout <<"main";
    return 0; 
} 

Below is the error i am getting.

prog.cpp:5:11: error: expected constructor, destructor, or type conversion before '(' token
     printf("one id defined");
           ^
  • 3
    You cannot execute code outside of any function. The only exception is initalization of objects. – Yksisarvinen Nov 26 '19 at 09:36
  • You can only call a function from within `main()`, another function or method. Your call to `printf` is not within such a scope. – Rene Nov 26 '19 at 09:36
  • To print message during compile time: https://stackoverflow.com/questions/3826832/is-there-a-portable-way-to-print-a-message-from-the-c-preprocessor – VLL Nov 26 '19 at 09:37
  • It would help if you explained what you expected this to do. When were you expecting the output to occur? – David Schwartz Nov 26 '19 at 09:37
  • Also this feels like you are using macros for something they are not intended for. And if you do use macros, always give them full uppercase names (like ONE) to avoid confusions when you read the code months later! – AlexGeorg Nov 26 '19 at 09:39

1 Answers1

4

It is not clear what this code is supposed to achieve, look at the expanded code to see what is wrong (-E for gcc). It will be something similar to:

#include <iostream>
using namespace std;


printf("one id defined");

void func1(); 
void __attribute__((constructor)) func1(); 
void func1() 
{ 
        printf("before"); 
} 
int main() 
{ 
    cout <<"main";
    return 0; 
} 

But you cannot call a function in file scope. There could be a declaration/definition, thats why the compiler expects a constructor, destructor, or type conversion.

PS: you include <iostream> but then use printf. Thats a bit odd. printf is in <cstdio>.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185