This question already has answers here:
Explanation of function pointers
(4 answers)
Closed 8 months ago.
I have the following scenario: I have a third party library and a header associated with it, that I'm using in my project. I completed my project and now I'm unit testing my code and I want to use a stub library, created by myself, for the third party library.
The header for the third party library contains structures that looks like this:
typedef struct{
int (*init)(int * var);
void (*close)(void);
} AInterface
To create my stub version, I created a .cpp file, in which I include the header, and started to implement it like this:
int AInterface::*init(int* var)
{
return 0;
}
void AInterface::*close(void)
{}
But when I compile my code I get the following error: "stub.cpp:76:33: error: cannot declare pointer to ‘void’ member
void AInterface::*close(void)"
I have searched the internet but with no success.
My questions are:
what I am doing wrong here?
is there another way to implement the stub?
I have also tried to implement the stub like this:
int initAInterface(int * var);
int (AInterface::*init)(int * var) = &initAInterface;
int initAInterface(int* var)
{
return 0;
}
But I get the following error:
error: cannot convert ‘int (*)(int*)’ to ‘int (AInterface::*)(int*)’ in initialization
int (AInterface::*init)(int* var) = &initAInterface;
Also I have no main in my stub .cpp file.
Those are function pointers and expect you to give static functions to them, then pass the struct to the library
//#################################################################
//Library header
typedef struct {
int (*init)(int* var);
void (*close)(void);
} AInterface;
//#################################################################
//A CPP file somewhere
//You might need extern "C" if you're mixing C and C++
#include "LibraryHeader.h"
int myInitFuction(int* var)
{
std::cout << "I wrote the init function for this" << std::endl;
return 0;
}
void myCloseFunction(void){
std::cout << "I wrote the close function for this" << std::endl;
}
//Or some other function doesn't need to be main if it's not the entry point
int main()
{
AInterface myInterface;
myInterface.init = myInitFuction;
myInterface.close = myCloseFunction;
SomeLibraryFuction(&myInterface);
}
Related
I would like to make a function that can print the contents of another function without breaking the functionality of the copied function.
For example:
int functionToCopy()
{
int a{ 5 };
int b{ 6 };
return a + b;
}
void printCopiedFunction()
{
some magical code to print the contents of the first function;
}
int main()
{
std::cout << functionToCopy() << '\n';
std::cout << printCopiedFunction() << '\n';
return 0;
}
Output:
11
int functionToCopy()
{
int a{ 5 };
int b{ 6 };
return a + b;
}
I'm only a beginner and C++ is my first language. I've done a lot searching and thinking but the only way I could think of is just literally copying the function and making a 2nd function a string, which would double my code and I'd rather avoid that. The program I'd like to do this with currently has 26 functions that would need copying like that so a single function that can be reused would be much preferred.
std::string copiedFunction()
{
std::string str{ R"(
int functionToCopy()
{
int a { 5 };
inb b { 6 };
return a + b;
})"
};
return str;
}
Any help is much appreciated! This is the only time I've ever asked for help like this on a forum but I think this is just beyond my abilities at this point. I understand this may not be possible or it may be very complex and just beyond my scope at this time. Thank you in advance!
C++ does not have reflection so you can't directly do this using the language alone. But you can do it by moving the function to a header file, #includeing that file in your .cpp file, and also building the header file into an object file which makes it contents available as a constant string.
First, put this in foo.h:
inline int functionToCopy()
{
int a{ 5 };
int b{ 6 };
return a + b;
}
Then, using the information from https://stackoverflow.com/a/46221837/4323 use objcopy to create an object file:
objcopy --input binary --output elf64-x86-64 foo.h foo.o
Then change your main file like this:
#include <iostream>
#include <string_view>
#include "foo.h"
extern "C" const char* _binary_foo_h_start; // defined in foo.o
extern "C" const char* _binary_foo_h_size;
std::string_view printCopiedFunction()
{
return {_binary_foo_h_start, _binary_foo_h_size};
}
int main()
{
std::cout << functionToCopy() << '\n';
std::cout << printCopiedFunction() << '\n';
}
And link foo.o into your executable at build time.
Note that objcopy is available on Linux and some other systems, you may need to look for an equivalent on your platform. For example if you have xxd: https://stackoverflow.com/a/411000/4323
On Windows you can embed the text file (which is the header file) as a "resource" in your executable, and load the resource at runtime, like this: Embed Text File in a Resource in a native Windows Application
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 2 years ago.
I'm having some difficulty reproducing an example program of Object-Oriented Programming Using C++ described in "Encapsulation and Type Extensibility."
For simplicity's sake, I've cut out most of the code to focus on the specific error at hand:
#include <iostream> // Access standard IO library
#include <string> //Access type 'string'
using namespace std; //Use standard library namespace
const int max_length = 255;
class my_string {
public:
void assign(const char* st);
int length() const { return len; }
void print() const
{ cout << s << "\nLength: " << len << endl; }
private:
char s[max_length];
int len;
};
int main()
{
my_string one;
one.assign("I'm sorry Dave, I'm afraid I can't do that.");
one.print();
system("PAUSE");
}
When I try to compile, I get the error message:
[Linker error] undefined reference to 'my_string::assign(char const*)'
I'm not sure what I'm doing wrong. My best guess is that assign is incorrectly defined, since the main() block seems fine.
Edit:
The complete example as written in the book is:
In file string1.cpp
const int max_len = 255;
class my_string {
public:
void assign(const char* st);
int length() const { return len; }
void print() const
{ cout << s << "\nLength: " << len << endl; }
private:
char s[max_length];
int len;
};
int main()
{
my_string one, two;
char three[40] = {"My name is Charles Babbage."};
one.assign("My name is Alan Turing.");
two.assign(three);
cout << three;
cout << "\nLength: " << strlen(three) << endl;
if (one.length() <= two.length())
one.print();
else
two.print();
}
Linking and compiling errors are two different things. A compiler error means that you did something wrong in the syntax.
A linking error tells you that there is a part missing when the linker tries to put your program together.
[Linker error] undefined reference to 'my_string::assign(char const*)'
This error tells you that somewhere the promise was made to the compiler that my_string::assign(char const*) exists and can be used (by a declaration void assign(const char* st);). But in the linking step the linker cannot find that function.
If the error references a function that you have written, then you might have forgotten the definition of it or have mismatching signature between declaration and definition.
The compiler can't find it's definition.
Usually there is a header file (.h) where the class' declaration is put, including as less as possible and a source file (.cpp) that includes all the definitions.
The header file declarations tells the compiler which methods shall be available (as a promise),
the source file should contain the definition of the functions that are declared in the header file.
If they aren't defined, meaning there is no body for that function, it can't be executed. In your book, the code is both declared and defined, by writing the methods inside the class' definition.
You could do the same:
public:
void assign(const char* st) {
/* implementations of the assign method here
(or leave it empty for this example, but rather don't)*/
};
int length() const { return len; };
...
I just got a sample of code, which cannot be modified:
#include <iostream>
#include "Image.h"
#include "Ppm.h"
int main() {
Image* ob = 0x0;
try
{
ob = new Ppm("lena.ppm");
long kolor = countColors(*ob);
std::cout << "Unikalnych kolorow: " << kolor << '\n';
}
catch (ImageError& e)
{
std::cout << e.what() << std::endl;
}
delete ob;
return 0;
}
I am confused with line
long kolor = countColors(*ob);
Two questions:
1) should this function be static?
2) should it be in class Image, or in Ppm, which inherit from the first one?
I am confused with line
long kolor = countColors(*ob);
You say that the code cannot be modified, so this line is already there in the code, and I assume the code is compiling/linking OK?
If it compiles OK, the function declaration for countColors() must be getting included from either from Image.h or Ppm.h, or from a header file that one of them includes. It certainly isn't coming from iostream.
If it's linking successfully, the object file or library containing the function definition for countColors() must be getting included in the link step.
We can only guess at the signature of this function; something like:
long countColors(const Ppm& portablePixmap);
...or maybe...
long countColors(const Image& image);
Whatever the signature is, it would not be declared with the keyword static (outside of a class), unless it was only used in the same file it's implemented in.
1) should this function be static?
The short answer is: it's unlikely that it is declared as static (see why below), but that's probably not what you're really asking about.
We know countColors() isn't a class method or instance method, because if it were, you'd have to call it like this1:
long kolor = SomeClass::countColors(*ob); // (class method)
or
long kolor = some_instance.countColors(*ob); // (instance method)
So if it's not a class or instance method, is it static? Probably not; here's why:
Say you've defined a function foo in file foo.c:
void foo(void) { ... }
...you can call it from bar.c:
#include "foo.h" // Tells compiler about foo()
void bar() { foo(); } // COMPILES AND LINKS OK
...but if you had defined the function in foo.c using the static keyword:
static void foo(void) { ... }
...the linker treats it as private to foo.c, so you can't call it from bar.c or any other source file besides foo.c:
#include "foo.h" // Tells compiler about foo()
void bar() { foo(); } // COMPILE OK, BUT LINKER ERROR!
2) should it be in class Image, or in Ppm, which inherit from the first one?
'should' implies that you're looking for the right place to put this method, but you also stated that this code can't be modified.
Are you trying to call this method from your own code, and you're not sure which header file to include, or how to call it?
Sorry, I could give you a better answer if I understood what it was you wanted to do.
1 It's possible to do evil things with macros in C/C++ like #define countColors(x) SomeClass::countColors(x), but we'll ignore that possibility.
This question has derived from this one.
I have a working program which must be split into multiple parts. In this program is needed to use a variable (now it's a GTK+ one :P) many times in parts of the program that will end up in separated .cpp files.
So, I made a simple example to understand how to make variables available to the program parts. A modified version of the previous code would be:
#include <iostream>
using namespace std;
int entero = 10;
void function()
{
cout<<entero<<endl;
//action1...;
}
void separated_function()
{
cout<<entero<<endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
It is needed to split the code correctly, to have function(), another_function() and main() in separated .cpp files,and make entero avaliable to all of them... BUT:
In the previous question #NeilKirk commented:Do not use global variables. Put the required state into a struct or class, and pass it to functions as necessary as a parameter (And I also have found many web pages pointing that is not recommended to use global variables).
And, as far I can understand, in the answer provided by #PaulH., he is describing how to make variables avaliable by making them global.
This answer was very useful, it worked fine not only with char arrays, but also with ints, strings and GTK+ variables (or pointers to variables :P).
But since this method is not recommended, I would thank anyone who could show what would be the correct way to split the code passing the variables as a function parameter or some other method more recommended than the - working - global variables one.
I researched about parameters and classes, but I'm a newbie, and I messed the code up with no good result.
You need to give the parameter as a reference if you want the same comportement as a global variable
#include <iostream>
using namespace std;
// renamed the parameter to avoid confusion ('entero' is valid though)
void function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value
//action1...;
}
void separated_function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value again
//action2...;
}
int main( int argc, char *argv[] )
{
int entero = 10; // initializing the variable
// give the parameter by reference => the functions will be able to modify its value
function(entero);
separated_function(entero);
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
output:
10
11
12
Defining a class or struct in a header file is the way to go, then include the header file in all source files that needs the classes or structures. You can also place function prototypes or preprocessor macros in header files if they are needed by multiple source files, as well as variable declarations (e.g. extern int some_int_var;) and namespace declarations.
You will not get multiple definition errors from defining the classes, because classes is a concept for the compiler to handle, classes themselves are never passed on for the linker where multiple definition errors occurs.
Lets take a simple example, with one header file and two source files.
First the header file, e.g. myheader.h:
#ifndef MYHEADER_H
#define MYHEADER_H
// The above is called include guards (https://en.wikipedia.org/wiki/Include_guard)
// and are used to protect the header file from being included
// by the same source file twice
// Define a namespace
namespace foo
{
// Define a class
class my_class
{
public:
my_class(int val)
: value_(val)
{}
int get_value() const
{
return value_;
}
void set_value(const int val)
{
value_ = val;
}
private:
int value_;
};
// Declare a function prototype
void bar(my_class& v);
}
#endif // MYHEADER_H
The above header file defines a namespace foo and in the namespace a class my_class and a function bar.
(The namespace is strictly not necessary for a simple program like this, but for larger projects it becomes more needed.)
Then the first source file, e.g. main.cpp:
#include <iostream>
#include "myheader.h" // Include our own header file
int main()
{
using namespace foo;
my_class my_object(123); // Create an instance of the class
bar(my_object); // Call the function
std::cout << "In main(), value is " << my_object.get_value() << '\n';
// All done
}
And finally the second source file, e.g. bar.cpp:
#include <iostream>
#include "myheader.h"
void foo::bar(foo::my_class& val)
{
std::cout << "In foo::bar(), value is " << val.get_value() << '\n';
val.set_value(456);
}
Put all three files in the same project, and build. You should now get an executable program that outputs
In foo::bar(), value is 123
In main(), value is 456
I prefer to provide a functional interface to global data.
.h file:
extern int get_entero();
extern void set_entero(int v);
.cpp file:
static int entero = 10;
int get_entero()
{
return entero;
}
void set_entero(int v)
{
entero = v;
}
Then, everywhere else, use those functions.
#include "the_h_file"
void function()
{
cout << get_entero() << endl;
//action1...;
}
void separated_function()
{
cout << get_entero() << endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<< get_entero() <<endl;
//something else with the mentioned variables...;
return 0;
}
If you do not plan to modify the variable, it is generally ok to make it global. However, it is best to declare it with the const keyword to signal the compiler that it should not be modified, like so:
const int ENTERO = 10;
If you are using multiple cpp files, also consider using a header file for your structures and function declarations.
If you are planning on modifying the variable, just pass it around in function parameters.
This question already has answers here:
get function member address
(2 answers)
Closed 8 years ago.
I am trying to use function pointer in a c++ class but got an error.
#include <cstdio>
#include <iostream>
using namespace std;
class abc{
public:
void hello(){
printf("Hello world\n");
}
abc(){
void (*hw)(void);
hw = &hello;
hw();
}
}
int main()
{
abc ab;
return 0;
}
Error
error: cannot convert ‘void (abc::*)()’ to ‘void (*)()’ in assignment
But the following code works for me which is in code base. Can anyone please help me to find out the difference?
void hello(){
printf("Hello world\n");
}
int main()
{
void (*hw)(void);
hw = &hello;
hw();
return 0;
}
Function pointers are (unfortunately) completely different from method pointers, as the error is trying to indicate. This is because the object that the method works on needs to be passed in somehow, which is what makes methods fundamentally different from functions in the first place (and obviously affects how the call is done through the pointer). Method pointers are not even always the same size (and can be significantly larger than a function pointer) when multiple/virtual inheritance comes into play.
You need to declare a method pointer, and call it on behalf of an object of the right type using one of the esoteric .* or ->* operators:
class abc {
public:
void hello(){
printf("Hello world\n");
}
abc() {
void (abc::*hw)();
hw = &abc::hello;
(this->*hw)(); // or (*this.*hw)()
}
}