1

I wrote the following function:

typedef float (*flIntPtr)(char);
flIntPtr c(int i) {
    flIntPtr pt = &b;
    return pt;
}

float b(char c) {
....//do something
}

Then visual studio reported that b is an undeclared identifier. I have go through the examples of possible causes to C2065:undeclared identifier below: Compiler Error C2065

To avoid typo or similar problem, I used single letters as function names, and so on. I also went through similiar questions provided by stackoverflow, there I noticed a similar problem hence I thought it might be caused by mistakenly written expression of the function pointer or type mismatch, since I didn't think my typedef part is wrong, I tried to change flIntPtr pt = &b; to flIntPtr pt = b; and flIntPtr pt = *b; but the error remained. Thus, I am once again asking for your technical support.~

7
  • 1
    That is simply illegal. stackoverflow.com/questions/31387238/… Commented Jan 26, 2021 at 10:26
  • 3
    In this example identifier b is indeed undeclared at the point where its address is taken. Also use of single letters as names is what typically leads to typos. In this case it also immediately leads to shadowing of function c by argument c. Commented Jan 26, 2021 at 10:31
  • 1
    Quick fix: put function b before c... Commented Jan 26, 2021 at 10:38
  • This is the same situation as int f() { return g(); } int g() { return 0;}. Commented Jan 26, 2021 at 10:53
  • 1
    The compiler goes thru the code once. Commented Jan 26, 2021 at 12:52

1 Answer 1

2

Your compiler tries to understand your code by digesting it from the top to bottom. This means that you need to have a inverted tree like structure (meaning that you need to have all the dependencies of a dependent somewhere on the top of it). When you don't have it, the compiler will flag an error.

int main()
{
    foo();    // <-- Here the compiler doesn't know that a function called foo is there somewhere so it'll flag an error.
    return 0;
}

void foo() {}

For this, what you need is Forward Declarations. These basically tell the compiler "Hey man, there's a function named 'foo' somewhere. Don't flag an error and be a complete moron let the linker handle it.". It'll look something like this,

void foo();    // <-- This is the forward declaration.
int main()
{
    foo();    // <-- Now the compiler will leave it alone for the linker to resolve this.
    return 0;
}

void foo() {}

This is not only for functions, its the same for classes and structs too. These are specially useful when it comes to circular dependencies.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.