Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force the compiler to declare functions in C/C++ itself?

Tags:

c++

g++

The problem:
I hate writing headers or declaring my functions if my computer can do it faster.
And it is the case.
What I tried to do:
I tried to declare a function foo after the main function.
But the compiler returns an error:
error: ‘foo’ was not declared in this scope
The code:

#include <iostream>

//no function declaration is allowed, please.
//no other header is allowed, please.

void main() {
    foo();
}

void foo() {
    std::cout << "The compiler is smart now!" << std::endl;
}

I accept to change the compiler if gcc/g++ is not able to compile this c++ code.
Any response will be greatly thanked.

like image 354
iohsfush Avatar asked Oct 12 '19 09:10

iohsfush


1 Answers

This is not possible with freestanding functions as the languages require at least a function prototype to call it. Having said that, in C++ you can use classes to achieve a similar result:

class Main {
public:
    static int main() {
        foo();
        return 0;
    }
    static void foo() { }
};

int main() {
    return Main::main();
}

Whether or not this is a good practice is a different discussion.

like image 182
Ayxan Haqverdili Avatar answered Oct 05 '22 00:10

Ayxan Haqverdili