-5

Let's say I have the following function in a static library libutil (with the definition in one of the library's translation units, so it can't be inlined while compiling the caller's translation unit):

consteval int square(constexpr int x) {
    return x * x;
}

And a function call in an executable hello which links against libutil:

int main() {
    constexpr result = square(5);
    printf("%d\n", result);
}

It was pointed out to me that C++ requires evaluation at "compile time", but with LTO some of the code generation is done at link time. Is this still considered "compile time" enough to do consteval evaluation? Is it compiler-dependent?

11
  • 2
    Most likely, the compiler is going to compile it down to printf("%d\n", 25); and not leave any work to the linker. I also won't be surprised if the code for square isn't even present in the library at all. Commented Aug 6 at 19:27
  • What does it mean, “from outside the library”? I'm serious. Commented Aug 6 at 19:35
  • What is very important is that you should describe if it is an "inline consteval" function in a header file or not. If your function is in a C++ file it won't be visible to the linker at all, only to the translation unit it is defined in. And no it should not be compiler dependent. Commented Aug 6 at 19:41
  • 1
    You can write your own answer. Commented Aug 6 at 19:57
  • 1
    “At compile time” means “while building the application”, which includes linking. It’s in contrast to “at runtime”. Commented Aug 6 at 19:59

1 Answer 1

0

From Igor Tandetnik:

cppreference has this to say: (1) a consteval specifier implies inline; and (2) The definition of an inline function must be reachable in the translation unit where it is accessed. I'm 99% sure you won't be able to hide the definition of consteval function in the library; you'd have to put it into the header.

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

3 Comments

It won't let me accept my own answer... but this is the correct answer.
It should allow you to accept in a day or two. Come back in a few days. Heck someone may come up with an even better/more complete answer full of C++ Standard references and a caveat or two while you wait.
From the help center: "You can also accept your own answer, but you must wait 48 hours to do so." So two days before you can accept this answer.

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.