Swig given "unknown namespace" errors on namespace aliasing - c++

I have a header file like
#include <MyUtils.h> // defines namespace MyUtils, and MyUtils::Math
namespace mum=MyUtils::Math;
class LocalClass{
public:
void eat( const mum::array& arr);
};
I have the usual %{ #include %}, %include structure in my .i file.
When I run swig I get:
Error: Unknown namespace 'MyUtils::Math'
How/why doesn't SWIG know about namespace aliasing?
Is there a work around other than using #ifndef SWIG preprocessor macros? (c.f. this discussion (I need to keep my c++ code independent of swig)
SWIG Version 2.0.4

Suppose to have a header
// MyUtils.h
namespace MyUtils {
namespace Math {
typedef int SomeType;
class array {
//
};
}
}
And another header
// MyHeader.h
#include <MyUtils.h>
namespace mum=MyUtils::Math;
class LocalClass {
public:
void eat( const mum::array& arr);
};
If you SWIG file looks like
// MySwigInterfaceFile.i
%module MySwigModule
#include "MyHeader.h
%include "MyHeader.h"
You run into trouble, SWIG will generate code that cannot compile for a number of reason
1) You need to include all headers, SWIG cannot recurse header, i.e. you must include MyUtils.h in your MySwigInterfaceFile.i before MyHeader.h, the same applies for the inclusion using the %include directive
2) You must write using namespace MyUtils::Math; following the inclusions using #include
3) To make SWIG aware of any typedefs inside nested namespaces, you must write
namespace MyUtils {
namespace Math {
%typedef int SomeType;
}
}
before the inclusions using %include
I recommend programmers to start out with many small projects to get hands-on experience with SWIG.

SWIG does appear to support namespace aliasing. I think the problem is likely in MyUtils.h; maybe there are pre-processor defines that you have to set in order for it to use the namespaces. You can define those on the SWIG command line.

Related

C++ how to extend class from different file without headers

I’m trying to do a basic polymorphism program and am having some problems.
I have 2 files, Currency.cpp and Dollar.cpp
Currency.cpp looks something like this
#include <iostream>
using namespace std;
class Currency{
/* code */
};
Dollar.cpp looks something like this
#include <iostream>
using namespace std;
class Dollar : protected Currency{
/* code /*
};
When I try to build paths between the files (command shift b on mac) it tells me that Currency is not recognized as a class (in Dollar.cpp that is). I’m not supposed to use header files as this is for an assignment that specifies so. What am I supposed to do?
I use vs code on a 2020 m1 Mac if that has anything to do with it
Edit:
Thanks for all the feedback. From what I can tell what I'm asking here isn't possible. This assignment is for a data structures and algorithms class that accepts multiple languages, so maybe the teacher is rusty in c++ or something. I'm just gonna use header files and the professor will just have to deal with it lol.
I’m not supposed to use header files as this is for an assignment that specifies so.
The code will not work as shown. Dollar.cpp needs to know what the Currency class looks like in order to use it.
The ideal solution is to use a header file to share declarations across translation units, use the .cpp files to implement definitions, eg:
Currency.h:
#ifndef CurrencyH
#define CurrencyH
class Currency{
/* code */
};
#endif
Currency.cpp:
#include <iostream>
#include "Currency.h"
using namespace std;
// implement Currency's methods as needed...
Dollar.cpp:
#include <iostream>
#include "Currency.h"
using namespace std;
class Dollar : protected Currency{
/* code /*
};
But, since that is not an option for you, you have no choice but to copy the entire Currency class declaration into Dollar.cpp directly, and make sure it exactly matches the class declaration in Currency.cpp to avoid any ODR violations, eg:
Currency.cpp:
#include <iostream>
using namespace std;
class Currency{
/* code */
};
// implement Currency's methods as needed...
Dollar.cpp:
#include <iostream>
using namespace std;
class Currency{
/* code */
};
class Dollar : protected Currency{
/* code /*
};

When I split up my C++ class into a header and implementation I get 20 compiler errors which don't make sense

I was splitting up my program into a header and implementation file per usual, however, when I tried to run the code, I got a ton of compile errors. This seems to be an issue with my computer or IDE, but I have not seen it before. This should be relatively simple as it is for a class project.
The code is as follows:
colorPicker.h
#pragma once
class colorPicker {
private:
string colorArray[7];
public:
colorPicker();
void printAllColors();
string randomColor();
};
colorPicker.cpp
#include "colorPicker.h"
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
colorPicker::colorPicker() {
colorArray[0] = "Red";
colorArray[1] = "Green";
colorArray[2] = "Purple";
colorArray[3] = "Yellow";
colorArray[4] = "Orange";
colorArray[5] = "Indigo";
colorArray[6] = "Pink";
}
void colorPicker::printAllColors() {
for (int i = 0; i < 7; i++) {
cout << colorArray[i] << endl;
}
}
string colorPicker::randomColor() {
srand((unsigned)time(0));
int j = 0;
j = rand() % 7;
return colorArray[j];
}
main.cpp
#include "colorPicker.h"
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main() {
colorPicker p;
p.printAllColors();
cout << "Random Color: " << p.randomColor() << endl;
system("pause");
return 0;
}
There are 20 errors given by the compiler, however, they all seem to be stemming from two undeclared identifiers which are most definitely declared. I am at a loss for what I could possibly do to fix it, and this project is due Sunday. Thank you.
Here are the errors
Tons of Errors
You need #include "colorPicker.h" in colorPicker.cpp. Each .cpp file is handled basically independently by the compiler and they are all joined at the end by the "linker." When the compiler looks at colorPicker.cpp without an include of the corresponding header, it's at a loss as to the definition of all the classes you're working with.
There are a few things you are doing wrong. I'll just pick on a couple.
Firstly, each header file you write should be self-contained - in the sense that, if it relies on content of some other headers, it includes that header. If a compilation unit (a formal name for a source file with a .cpp in your case) includes your header, it should not have to include something else your header depends on.
Second, it is a bad idea for a header to rely on any using directive, such as using namespace std. There are plenty of explanations of that available, so I won't repeat.
To understand the above, look at colorPicker.h
class colorPicker {
private:
string colorArray[7];
public:
colorPicker();
void printAllColors();
string randomColor();
};
Firstly, this depends on string, but there is no definition of string visible in the header file. Usage of that type depends on the standard header <string>.
Second, that string type is within namespace std. So your header relies on the compilation unit (the source file that includes your header) having previously used a using directive i.e. using namespace std.
To fix these two problems, change the header to
#ifndef SOME_MACRO_UNIQUE_TO_YOUR_COLOR_PICKER_HEADER
#define SOME_MACRO_UNIQUE_TO_YOUR_COLOR_PICKER_HEADER
#include <string>
class colorPicker
{
private:
std::string colorArray[7];
public:
colorPicker();
void printAllColors();
std::string randomColor();
};
#endif
(I've also done some minor changes of layout, since I have various reasons to prefer that.
However, the #include <string> means that this version will not fail to compile, as yours does, if it is included by a compilation unit that does not have #include <string>.
The usage of the fully qualified name std::string, rather than string, also means there is no dependence on the using directive using namespace std. It also means compilation errors can't be triggered in your header if your compilation unit has another using directive.
I've also used an include guard, rather than #pragma once. Although most modern compilers support #pragma once, it is actually not standard C++ (a #pragma, by definition in the standard, is a compiler-specific hook). Include guards are supported in standard C++.
If you've done that, your code should mostly compile as is. However, optionally, you may wish to
remove the using directives using namespace std from your other files. If you do that, you will need to change the definition of colorPicker::randomColor() in colorPicker.cpp so it returns the fully qualified type std::string rather than string.
Remove #include <string> from files that have #include "colorPicker.h". This is possible, since colorPicker.h now includes <string>. This step is optional, since there is no problem with including standard headers more than once in a compilation unit.
A few other notes
In C++, although it is not a major concern, it is usually considered better to use include <cstdio> and <cstdlib> rather than the C headers <stdio.h> and <stdlib.h>.
Your code is calling srand((unsigned)time(0)) whenever colorPicker::randomColor() is called. It is better to only call it once in an entire program, not in a function that may be called multiple times.
A header file should be self-contained as far as #includes go. That means that you should be able to #include the header file without having to include other stuff before it!
Your colorPicker.h does not meet that requirement. It apparently uses std::string from the standard library but does not have an #include <string> on top, so everyone who uses colorPicker.h has to remember to put an #include <string> before it. That's pretty annoying.
Even worse, colorPicker.h refers to std::string as string, which implies a using std::string; or using namespace std; somewhere before any #include "colorPicker.h" line, and both of those are very bad coding style in C++, if not used in tighter scopes.
Here's how to fix the header file:
#pragma once
#include <string>
class colorPicker {
private:
std::string colorArray[7];
public:
colorPicker();
void printAllColors();
std::string randomColor();
};
As far as your *.cpp files go, I can see that you are using #include "stdafx.h". Why? It's a non-standard Microsoft thing completely unnecessary in your case. You are also using it incorrectly. It must be the first include. Just remove it entirely.
Some other suggested cleanup:
using namespace std; lines in *.cpp files is not as bad as in header files, but if I were you, I'd just get rid of it completely. Just use complete names. Say std::cout, not cout. And so on. It's just the most consistent way and it avoids a lot of trouble.
You include a lot of headers which you don't need. For example, what's <ctime> for?
Don't use system("pause");. Do not look for artificial ways of pausing a command-line program.
You may need add head file and in colorPicker.h.
And the std namespace is needed while using string.
BTW, the header guards is recommended strongly.
#ifndef COLOR_PICKER_H
#define COLOR_PICKER_H
#pragma once
#include <string>
class colorPicker {
private:
std::string colorArray[7];
public:
colorPicker();
void printAllColors();
std::string randomColor();
};
#endif

Clang unknown class name 'exception'

For some odd reason I am having difficulties throwing an exception in C++. I throw without catching std::invalid_argument from the stdexcept header file. I have no real intention of catching as i want the application to fail anyway if the error occurs.
It seemed to be working fine until I #included the function definition class into the namespace of the header declaration. It was added outside of the namespace prior since they are template definitions and I wanted to separate the header from its definition; however, I realized this caused a subtle issue that I did not realized until only recently.
Is their something I am missing? I am using clang btw
Project Compilation
.
.
.
.
.
Compiling CPP file TrieTest.cpp ...
In file included from TrieTest.cpp:4:
In file included from ./Trie.hpp:62:
In file included from ./Trie.cpp:2:
/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/stdexcept:55:30: error: unknown class name 'exception'; did you mean
'::std::exception'?
class logic_error : public exception
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/exception:60:9: note: '::std::exception' declared here
class exception
^
In file included from TrieTest.cpp:4:
In file included from ./Trie.hpp:62:
In file included from ./Trie.cpp:2:
/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/stdexcept:112:32: error: expected class name
class runtime_error : public exception
^
2 errors generated.
EDIT: A bit of the src
Also I compile with
clang++ -Wall -Wextra -g -std=c++11 TrieTest.cpp -o TrieTest;
"Trie.h"
#ifndef COM_WORDGAME_UTILITY_TRIE_HPP
#define COM_WORDGAME_UTILITY_TRIE_HPP
#include <string>
using std::string;
namespace wordgame_utility{
template<typename value>
class Trie{
...Trie Function Declarations
};
//The compiler may not complain initialliy however
//Templates cause visibility issues with user code and is normally defined in the header
//this is a work around
#include "Trie.cpp"
}
#endif
"Trie.cpp" head -n 8
#include "Trie.hpp"
#include <stdexcept>
using namespace wordgame_utility;
template<typename value>
using TrieNode = typename Trie<value>::TrieNode;
...Trie Function Definitions
You have a cyclic include in your code.
Trie.hpp includes Trie.cpp which includes Trie.hpp. This is not meant to work in C++, where include is a literal inclusion (think, copy/pasting the included file at the point of the #include directive).
You need to define template methods into the header, or into a third file, that's all there is.
What is the effect of this cycle ? In general, poor error messages, as you can see by yourself.
In your case... let's play preprocessor ourselves:
// begin #include "Trie.hpp"
#define COM_WORDGAME_UTILITY_TRIE_HPP
// begin #include <string>
namespace std {
...
}
// end #include <string>
using std::string;
namespace wordgame_utility{
template<typename value>
class Trie{
...Trie Function Declarations
};
//The compiler may not complain initialliy however
//Templates cause visibility issues with user code
// and is normally defined in the header
//this is a work around
// begin #include "Trie.cpp"
// begin #include "Trie.hpp"
// -- empty because of the include guards --
// end #include "Trie.hpp"
// begin #include <stdexcept>
namespace std {
class logic_exception: public exception { };
}
// end #include <stdexcept>
using namespace wordgame_utility;
template<typename value>
using TrieNode = typename Trie<value>::TrieNode;
...Trie Function Definitions
// end #include "Trie.cpp"
} // namespace wordgame_utility
// end #include "Trie.hpp"
As you can see, it's a mess. The combination of using #include within an open namespace and having cyclic includes is downright ugly.
Fortunately, in the (near ?) future, this will be improved if modules are adopted, which are just a much saner alternative to textual inclusion.

Using namespaces inside template implementation files

To keep class definition in header file clean, I decided to move implementations of templated functions into another *.h file, which I include in the main header. Now I would like to make use of using namespace there, to make code more readable.
But using namespaces would affect the whole application, since the file gets included in the header which itself gets included in the whole application. The using of the namespaces would spread out of the file.
How can I handle this?
You can put using namespace XX inside function definitions to scope the using declaration to that function:
int func( ...args... )
{
using namespace std;
// ... body of function
}
Use a namespace alias.
namespace submod_ = topspace::other_project::module::submodule;
Then you can use submod_ wherever you would require the very long namespace.
This requires you to still use submod_ where you would have the long namespace qualifier. In that sense, it doesn't exactly answer your question. But I would argue that the explicitness of the qualification aids readability and helps prevent mistakes.
There are real examples of StackOverflow questions where a "using" declaration brought in "lurking" functions which the code author did not realize.
You can place the using namespace in the namespace of your 'main header':
Header.h
#include <string>
namespace Test
{
using namespace std;
string f()
{
return "Test";
};
}
main.cpp
#include "Header.h"
int main()
{
Test::f();
string test; // Error: identifier "string" is undefined
std::string test;
return 0;
}

Can I undo the effect of "using namespace" in C++?

With using namespace I make the whole contents of that namespace directly visible without using the namespace qualifier. This can cause problems if using namespace occurs in widely used headers - we can unintendedly make two namespaces with identical classes names visible and the compiler will refuse to compile unless the class name is prepended with the namespace qualifier.
Can I undo using namespace so that the compiler forgets that it saw it previously?
No, but you can tell your coworkers that you should never have a using directive or declaration in a header.
As others said, you can't and the problem shouldn't be there in the first place.
The next-best thing you can do is bring in your needed symbols so that they are preferred by the name look-up:
namespace A { class C {}; }
namespace B { class C {}; }
using namespace A;
using namespace B;
namespace D {
using A::C; // fixes ambiguity
C c;
}
In some cases you can also wrap the offending includes with a namespace:
namespace offender {
# include "offender.h"
}
No, C++ Standard doesn't say anything about "undo". The best you are allowed to do is to limit scope of using:
#include <vector>
namespace Ximpl {
using namespace std;
vector<int> x;
}
vector<int> z; // error. should be std::vector<int>
But unfortunately using namespace Ximpl will bring all names from std namespace as well.
Not to my knowledge... But as a rule I only use "using namespace" in .cpp files.
The closest, that I'll try to use in header files is following:
//example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
/**
* hating c++ for not having "undo" of using namespace xx
*/
#define string std::string
#define map std::map
class Example {
public:
Example (const char *filename);
Example (string filename);
~Example ();
private:
map<string,complicated_stuff*> my_complicated_map;
};
#undef string
#undef map
#endif //EXAMPLE_H_
after all, defines are #undef -able.
There are 2 problems:
1. it is ugly
2. separate #define and #undef for each name from the corresponding namespace are used
As stated you should not use using namespace sth in header files. When you need functionality from a namespace in your implementation you can leverage scopes like this:
void func() {
// some code agnostic to your namespace.
{
using namespace sth;
// some code aware of sth.
}
// some other code agnostic to your namespace.
}