0

I have an embedded project containing both c files (drivers from the SDK) and c++ (.cpp) files (my own code). I'm trying to set up an interrupt service routine. I've found it works fine if the ISR is in a .c file. However, the exact same function moved into a .cpp file does not work.

In MK64F12_Vector.s;

_vectors:
    ...
    .word PORTD_MyIRQHandler

Some related initialization code that is called once at start-up;

CLOCK_EnableClock(kCLOCK_PortD); 
EnableIRQ(PORTD_IRQn);
PORT_SetPinInterruptConfig(PORTD, 0, kPORT_InterruptFallingEdge);

In .c file;

void PORTD_MyIRQHandler()
{
  while (1) ; // put breakpoint here
}

The above works fine if PORTD_MyIRQHandler() is in a .c file. But if I move it to a .cpp file (where I want it!) I get the error below. Note I am just copying & pasting it without changing anything.

(.vectors+0x138): undefined reference to `PORTD_MyIRQHandler'

Is there something else I need to do to get it to work? A compiler or linker option perhaps? I've tried the following without success;

__attribute__((interrupt)) void PORTD_MyIRQHandler() {..}

#pragma interrupt
void PORTD_MyIRQHandler() {..}

I am using Segger Embedded Studio with gcc.

3
  • 2
    Are you missing an extern "C" in the C++ code? Name mangling could be the culprit. Commented Sep 16, 2018 at 4:23
  • 1
    @RobertPrévost yes, that was it. Thanks! If you want to post that as an answer I'll accept it. Commented Sep 16, 2018 at 4:29
  • An endless loop in an interrupt handler is an abolute no-go. Said that: you stumbled upon one of the differences between C and C++. Why do you expect two different languages to behave the same? Commented Sep 16, 2018 at 11:46

1 Answer 1

2

Try

extern "C" void PORTD_MyIRQHandler(){
}

C++ adds characters to the fuction name that depend on the input and return value types of the function.

This feature, type name mangling, exists to avoid linking functions with wrong kinds of parameters and to allow function overloading. Using extern "C" disables that.

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

2 Comments

This will not magically turn the code in the function into C code. It still will be compiled as C++. See my comment at the question, too.
@toohonestforthissite : I am not sure what your point is - while true, the answer does not suggest that the resulting code is C. It gives it C linkage, restricts its interface to be C compatible and in this case allows symbol resolution with the reference in the .s file. The advantage is that the function body can use C++ specific constructs.

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.