2

Context

I'm writing a function that uses other functions which are only needed in that main function. The purpose of that main function is to make some sort of kit that will call the required functions.

Exemple

int a(int x) // make x = 10 in a recursive way and its purpose is limited // to be used with function b { if (x == 10) return x; else if(x<10) return a(x+1); else return a(x-1); } int b(int x, int allow_b) // This is only an exemple, function b simply call function a if required. { if (allow_b == 1) return a(x); else return x; } 

Question

Since function 'a' only exist to be used by 'b', should there be something particular to be done in the header file or it should only be commented over the function 'a' is used by 'b' ?

Is there something wrong with that kind of approach?

Edit

I mean what should be declared in header, I'm not talking about writing function 'a' and 'b' in header file.

2 Answers 2

4

If function a is only used by b, then I see no need for it to be declared in any header file.

Put both functions in the same translation unit, and declare and define function a with static linkage, as an additional constraint, which will prevent it from being accessible from other translation units.

It's possible that for various logistical reasons the two functions must be in different translation units, which would require a to be declared in a header file. In that case, the only thing that can be done is to comment and document this. You might also consider setting up a separate namespace for a alone, to emphasize this.

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

4 Comments

I was just about to write almost exactly this answer. +1
I don't understand how to do so? I still have to declare a in header
No you don't. "void foo() {} int main() { foo(); }", this will compile and run. See: you called foo() from main(), and you didn't have to have any silly header file, anywhere, to do so.
Ah I understand, my function had default arguments, so it wouldn't be found, thanks
1

Your C++ file will contain the definitions (i.e., implementations) of a and b -- in the manner you have shown (a defined above/ahead of b).

What goes in your header file will only be the declaration of b. (Unless you have a strong valid reason, do not define your functions in a header file.)

You will provide the header file and a library file to your clients, and they will not know anything about a.

If you do not want any sort of linkage for a whatsoever, look up anonymous namespace. (C abuses the static keyword for the same purpose, and hence is available in C++ as well)

namespace { int a(int x) { // whatever return x; } // end function definition } // end anonymous namespace 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.