Function pointer link stubs


Last week been test-driving some C code again and found that not much people are familiar with the "function pointer link stub". This is an excellent technique in C to dynamically replace library calls without adjusting the library.

Imagine, you are working on some embedded software. You will have a couple of libraries that you use, but you won't link to it when unit testing. Instead you stub them out. But, a link stub cannot be adjusted on run-time, so how do you handle this? With... "function pointer link stubs".

The idea is simple. You stub out the library and your stub calls a function pointer when its set. When not set, it just returns success.

Here is some example code:

.h (in a library where we cannot change the header)

int aLibraryCallWeCannotChange(int param);

----------------
aLibraryStub.h

extern int (*aLibraryCallWeCannotChangeFp)(int param);

-----------------
aLibraryStub.c

int aLibraryCallWeCannotChange(int param)
{
   if (aLibraryCallWeCannotChangeFp) aLibraryCallWeCannotChangeFp(param);
   return 0;
}

int (*aLibraryCallWeCannotChangeFp)(int param) = NULL;

-------------------------
TestThatUsesLibrary.cpp

TEST_GROUP(blah)
{
   void setup()
   {
       UT_PTR_SET(aLibraryCallWeCannotChangeFp, dynamicStubOfALibraryCall);
   }
}

Now it is easy to place the code of your stub close to your tests and you will never have to change the linker stub code.

Read more

Vibe Coding

Vibe Coding

สร้างผลงานในจังหวะของ AI Web Summit 2025 — Lisbon | Matt Wolfe, Replit ลองจินตนาการดูว่า… การเขียนโค้ดของคุณไม่ได้เหมือนกับพิมพ์คำสั่งในเทอร์มินัล แต่เหมือนกับ เล่นดนตรีร่วมกับวง — มีจังหวะ มีความรู้สึก และมีคู่หูที่เข้

By Chokchai
เอื้อมไปคว้าดาว

เอื้อมไปคว้าดาว

หลายคนอยากประสบความสำเร็จ องค์ประกอบที่สำคัญที่จะทำให้เราประสบความสำเร็จได้นั้น คือการที่เราสามารถสร้างผลงานที่มีคุณภาพสูงออกมาได้อย่างสม่ำเสมอ ไม่ใช่สร้างได้แค่เป็นครั้งคราวนะ ลูกฟลุ๊คแบบนั้นเพียงพอแค่สำหรับมือสมัครเล่น ถ้าจะเลี้ยงปากท้องยึดเอาเป็นอาชีพได้ เราต้องสร้างผลงานคุ

By Chokchai