Function pointer question

A

Adrian

Can anything bad happen by using a function pointer to a static
function in a different module?

Below is an example:

//FILE: main.cpp
#include <iostream>

typedef int(*func_ptr)(void);
func_ptr func();

int main(int argc, char *argv[])
{
func_ptr x=func();

int y=x();

std::cout << "y=" << y << std::endl;

return 0;
}


// FILE: func.cpp
static int func2(void);

typedef int(*func_ptr)(void);

func_ptr func()
{
return &func2;
}

static int func2(void)
{
// return some random int from mem;
int a;
int b;

return (a+b)*723;
}
 
F

Fei Liu

Adrian said:
Can anything bad happen by using a function pointer to a static
function in a different module?

In theory, you cannot access a static function from another translation
unit (i.e. a different module).

Fei
 
C

Clark Cox

In theory, you cannot access a static function from another translation
unit (i.e. a different module).

Not by name, but there is nothing wrong with using a function pointer
to access it.
 
O

Old Wolf

Can anything bad happen by using a function pointer to a static
function in a different module?

Your code is correct, altho it is better to
include the declration of func() in a header
file, because if you make a typo or a change
in one of the C++ files and not the other then
you will have undefined behaviour.

Also, some implementations (typically, crappy
embedded ones) fail to implement function
pointers properly so beware of that in advance.
 
R

red floyd

Old said:
Also, some implementations (typically, crappy
embedded ones) fail to implement function
pointers properly so beware of that in advance.

I find that hard to believe. Function pointers have been around since
the K&R days.
 
I

Ian Collins

Old said:
Also, some implementations (typically, crappy
embedded ones) fail to implement function
pointers properly so beware of that in advance.
Care to name and shame? I've never seen this in practice.
 
O

Old Wolf

I find that hard to believe. Function pointers have been around since
the K&R days.

Well, I've used several such systems, so believe
what you will. Typically what happens is that the
code for the function is on a code page that isn't
swapped in at the time (so it jumps to unrelated
code at the same location on the current page),
or that the system traps when a shared library
invokes a function pointer that points to a function
in the calling application.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top