C++ "use" namespace "before" declaration

60 Views Asked by At

I know that most code isn't organized this way at all, but for my specific purpose, DS&A problems, I would like my code in a single file and organized a specific way (with main on top)

int main(){
//arrange - i.e. create the input params, 
//act - run the answer code i.e. answers::myFunction(params)
//any kind of post analysis  -- lol assert?  
}

namespace answers{
answer implementations
}

The problem is that the answers namespace is being used before being declared (so it won't compile). In order to get my compiler to work I have to swap these i.e.

namespace answers{
answer implementations
}

int main(){
//arrange - i.e. create the input params, 
//act - run the answer code i.e. answers::myFunction(params)
//any kind of post analysis  -- lol assert?  
}

I don't like that (the main func is distracting at the bottom), I want my main func on top.

Is there any compiler option for any compiler that will allow me to organize my code this way?

Note: I am currently using g++ (Rev7, Built by MSYS2 project) 13.1.0

1

There are 1 best solutions below

0
user17732522 On

Is there any compiler option for any compiler that will allow me to organize my code this way?

No, it is a quite fundamental principle of C++ (and C) that names need to be declared before they are used (with some minor exceptions in templates).

You don't generally need to define the entities that you use before they are used though. So just declaring everything you need before main and then defining after main is generally fine.

In that case the declarations are often separated into a header file.