Can't figure out undefined reference error Topic is solved

Technical questions regarding the XTC tools and programming with XMOS.
andy-aic
Member++
Posts: 26
Joined: Thu Jun 27, 2024 3:38 pm

Can't figure out undefined reference error

Post by andy-aic »

Hi,

I have the following code:

Code: Select all

// stft.h
#include "xmath/xmath.h"

typedef struct {
    exponent_t exponent;
    headroom_t headroom;
} stft_state_t;

int stft(int64_t stft_output[], int samples[], stft_state_t *p_state);

Code: Select all

// stft.c
#include "stft.h"

int stft(int64_t stft_output[], int samples[], stft_state_t *p_state) {
    // Implementation
}

Code: Select all

// inferencer.cpp
#include "stft.h"

const int tone[1024] = { ... };

void calculate_stft(int32_t input[], int32_t output[]) {
    stft_state_t stft_state;
    int64_t stft_data[256];

    stft(stft_data, (int *)tone, &stft_state);
}
I keep getting the following error: inferencer.cpp: Error: Undefined reference to '_Z4stftPxPiP12stft_state_t'

I must have tunnel vision because I can't see what's wrong with the code. The only thing I have been able to figure out is that the code compiles fine if I comment out this line:

Code: Select all

stft(stft_data, (int *)tone, &stft_state);
Then it compiles and I only get warnings about unused variables. I confirmed that the compiler can see stft.h from inferencer.cpp. I just added a #define STFT_VALUE 0 in stft.h and I used that definition in inferencer.cpp without any issues. Not sure what's wrong with stft_state_t. I also tried renaming the typedef just to make sure that there aren't any name conflicts or something, but it still failed to compiled the program.

What is wrong with my code?
View Solution
andy-aic
Member++
Posts: 26
Joined: Thu Jun 27, 2024 3:38 pm

Post by andy-aic »

I figured it out. I had to do this in inferencer.cpp:

Code: Select all

extern "C" {
#include "stft.h"
}
It seems the problem had something to do with name mangling.
User avatar
upav
Verified
New User
Posts: 3
Joined: Wed May 22, 2024 3:30 pm

Post by upav »

Hey Andy,

From my experience working on AI applications on xs3a, I tend to put all C and C++ API in:

Code: Select all

// header_file.h or hpp

#if defined(__cplusplus) || defined(__XC__)
extern "C" {
#endif

void my_api();

#if defined(__cplusplus) || defined(__XC__)
}
#endif
This way all your c and cpp headers will be xc/cpp friendly, so you can include them anywhere. If it's too ugly for you, you can make a #define API_START and API_FINISH and put them at the beginning and the end of every header.

Cheers,
Pavel,
xmos software engineer
andy-aic
Member++
Posts: 26
Joined: Thu Jun 27, 2024 3:38 pm

Post by andy-aic »

Hi Pavel,

Thanks for the tip!