How to access function defined in namespace in other .cc file - c++

I have a file named test.cc
#include <stdio.h>
int doit(){
return 4;
}
namespace abc {
int returnIt(int a){
return a;
}
}
I can use doit(), but how can I use this function in namespace in my main.cc without using .h file:
using namespace abc;
int doit();
int main(int argc, const char * argv[]) {
cout<<returnIt(3)<<endl; // print 3
cout<<doit(); // print 4
return 0;
}

You can call functions by first declaring them. Example:
namespace abc {
int returnIt(int a); // function declaration
}
int main() {
abc::returnIt(3); // the declared function can now be called
Note that the declaration must be exactly the same as used elsewhere in the program. To achieve identical declarations across translation units, it is conventional to put the declaration into a separate file (called a header) and include that file using the pre-processor whenever the declaration is needed.

All you need is to simply write the functions before the main function. That way, the compiler has processed the function prototypes by the time it encounters them in main and can validate the function call.
int doit()
{
return 4;
}
int returnIt(int a)
{
return a;
}
int main(int argc, const char * argv[])
{
cout<<returnIt(3)<<endl; // print 3
cout<<doit(); // print 4
return 0;
}
In general, avoid using namespace;. It makes for code that can be broken or be rendered less readable due to incorrect variable/function usage. That is because too many symbols can occupy the same (global) scope.
If another library needs to used, as user4581301 pointed out, then it may be simpler to use eerorika answer/method.

Related

Does declaring variables and functions in same namespace get an error? [C++]

If I create a namespace Maths and use another library with a namespace named Maths, will I get an error for re-declaring a variable like PI or re-defining a function like add?
I ask because if I choose to not use namespaces, I should get an error for doing those things, right?
If I don't get an error using namespaces but I do when not using namespaces, isn't safer to just not use namespaces?
Thanks for your time.
First thing, namespace must be global and In different namespace you can have same function or variable, but in same namespace you can't have same variable declaration twice.
namespace A {
int i=10;
char i ='a';/** is not valid **/
void print() {
...
}
}
namespace B {
float i = 1.5; /** valid **/
void print() { /** valid **/
...
}
}
In above example in namespace A and B you have i of int type and i of float type respectively which is valid but In namespace A itself you can't have variable i of different types (considered as re-declaration)
Decided to test it myself:
//in file testnamespace.h
namespace test
{
int t = 1;
void fooo(){};
}
//in file testnamespace2.h
namespace test
{
int t=10000;
void fooo(){int x = -2;}
}
//in file test.cpp
#include "testnamespace.h"
#include "testnamespace2.h"
int main()
{
int ayyyeee = test::t;
foo();
return 0;
}
This gives an error for redefinition,multiple initialization.
All I was looking for.

Confusion about inline function

I have a question regarding inline function.
#include <iostream>
using namespace std;
class A
{
public:
inline void fun()
{
int i=5;
cout<<i<<endl;
}
};
int main()
{
A a1;
int i = 2;
a1.fun();
cout<<i<<endl;
return 0;
}
In above program, when function fun() was called, the compiler should have made copy of this function and insert into main function body because it is inline.
So, I have a question, Why doesn't compiler give an error of variable int i; being re-declared?
You seem confused about scopes. They're not "within the same" scope
You can declare multiple variables with the same name at different scopes. A very simple example would be the following:
int main()
{
int a; // 'a' refers to the int until it is shadowed or its block ends
{
float a; // 'a' refers to the float until the end of this block
} // 'a' now refers to the int again
}
Inline expansion is not pure text replacement (as opposed to macros).
Whether a function is inlined or not has no effect on semantics Otherwise the program would behave differently depending on whether the function was inlined or not, and return statements would not behave properly at all.

Visual Studio 2013 c++ function syntax error

I'm using VS 2013, for some reason in a C++ console application a simple function declaration will not work. What is going on?
I have #include iostream and the code is inside the int main () {...} body.
-TSR
UPDATE:
Here is the full program
Look at the comment in my program. You should write functions outside of the main method.
/* Wrong code
-----------------------------------------
*/
#include <iostream>
int main()
{
int printmessage ()
{
}
}
/* Correct code
----------------------------------------
*/
#include <iostream>
int printmessage ()
{
}
int main()
{
}
You are not allowed to define a function within another function, although you are allowed to declare one. So something like this is allowed:
int main()
{
void func1() ; // function declaration but not definition.
}
void func1()
{
//...
}
but this is probably what makes more sense for you:
int printmessage()
{
//...
}
int main()
{
}
Function definitions are only allowed in the namespace or class scope, from the draft C++ standard section 8.4 Function definitions paragraph 2 says:
[...]A function shall be defined only in namespace or class scope.
You cannot have a function definition inside the main loop. You can either use function prototyping before the main(int argc, char** argv) or define the function before the main.
// Either define your function here
void Foo() { }
// Or use this prototyping
void Bar();
int main ()
{
// Call your function here
Foo();
return EXIT_SUCCESS;
}
void Bar() { }
Hope this helps.
For the declaration of function inside another function, it is just the backward compatibility with C programming. I doubt if anyone ever use this anymore. Plus, this is C++ not C

VS2012 - Why is a function in the main file not visible in _tmain?

I'm fairly new to C++, and I'm starting out with this in a terminal application:
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
if ( argc < 1 )
{
printHelp();
return 1;
}
return 0;
}
void printHelp()
{
cout << "Usage:";
cout << "vmftomap [filename]";
}
However, I get the error "'printHelp' identifier not found" in _tmain. Since the function is declared directly beneath main, I'm assuming this is a namespace issue? I have read up on namespaces but I don't know what would apply in this case, since I haven't actually explicitly defined one for printHelp().
You have to declare your function before you invoke it. It is not necessary to define it, but the compiler must at least know about its existence in the moment it has to resolve a function call, which means it must have met a declaration for it during the processing of your translation unit (i.e. .cpp file):
#include "stdafx.h"
#include <iostream>
using namespace std;
// Declaration
void printHelp();
int _tmain(int argc, _TCHAR* argv[])
{
if ( argc < 1 )
{
printHelp();
return 1;
}
return 0;
}
// Definition
void printHelp()
{
cout << "Usage:";
cout << "vmftomap [filename]";
}
Of course, you could directly define the printHelp() function before main() instead, thus making it visible to the compiler at the point the function call is made:
#include "stdafx.h"
#include <iostream>
using namespace std;
// Definition
void printHelp()
{
cout << "Usage:";
cout << "vmftomap [filename]";
}
int _tmain(int argc, _TCHAR* argv[])
{
if ( argc < 1 )
{
printHelp();
return 1;
}
return 0;
}
In C++, files are parsed top-to-bottom. With a few exceptions, identifiers have to be declared before they are used. This means you must move the definition of printHelp() before _tmain(), or add a forward declaration above _tmain():
void printHelp();
The function has to be defined before using it.
Move printHelp above _tmain.
When you call a function in c++, before the call, you must either:
have a prototype of the function
have the definition of the whole function
in your case, you have neither.

Is it possible to put a function declaration within an unnamed namespace?

I have a file with a set of functions. For one of the functions, I want to write a helper function which basically takes a char * and skips all whitespaces.
Here's how I thought it should be done:
namespace {
const int kNotFound = -1;
void SkipWhitespace(const char *s); // forward declaration - doesn't seem to work?
}
void foo(const char *s1, const char *s2) {
// do some stuff
SkipWhitespace(s1);
SkipWhitespace(s2);
// continue with other stuff
}
void SkipWhitespace(const char *s) {
for (; !isspace(s); ++s) {}
}
But this gives me a compiler error. Do I need to put the definition within the unnamed namespace?
You have to define it in the anonymous namespace as well:
namespace {
...
void SkipWhitespace(const char *s); // forward declaration - doesn't seem to work?
}
void foo(const char *s1, const char *s2) {
...
}
namespace {
void SkipWhitespace(const char s*) {
for (; !isspace(s); ++s) {}
}
}
But unless there is a cyclic dependency, I'm not sure what the value of this is. Just declare and define the function in one go.
An unnamed namespace behaves as if it was replaced with a namespace with a uniquely generated name immediately followed by a using directive.
This means that your function declaration belongs to a namespace exactly as if the namespace actually had a name. As such, its definition should live in the same namespace : either simultaneously declare and define the function, or add an enclosing namespace {} around the definition (which works because all occurrences of the unnamed namespace in a translation unit refer to the same namespace).
namespace {
void SkipWhitespace(const char s*) {
for (; !isspace(s); ++s) {}
}
}
You probably need to see this topic as well:
Superiority of unnamed namespace over static?
BTW, why this function:
void SkipWhitespace(const char *s);
Why not this:
void SkipWhitespace(std::string &s);
??