Quirks of Emscripten Exported Functions in Visual Studio

As I start delving into Emscripten, I've encountered a puzzling issue with exporting functions for use in JavaScript. Working on a test project involving libsquish, the specific details aren't crucial to my question beyond the header/code filenames.

So, to simplify the test,

c/c++

//squish.h
extern "C" int main();
int main();

extern "C" int gsr();
int gsr();

//squish.cpp
int main()
{
    return 99;
}

int gsr()
{
    return 8675309;
}

Additional Options/Command Line

-s EXPORTED_FUNCTIONS="['_gsr','_main']" 

Javascript

main=Module.cwrap('main','number',null);
console.log(main());

GetStorageRequirements = Module.cwrap('gsr', 'number',null);
console.log(GetStorageRequirements());

Javascript Console (Chrome)

99
Assertion failed: Cannot call unknown function gsr (perhaps LLVM optimizations or closure removed it?)
Assertion failed: Cannot call unknown function gsr (perhaps LLVM optimizations or closure removed it?)

Furthermore, optimization is disabled (O0).

So, why is one function recognized while the others are deemed "unknown"? Despite sharing similar characteristics, it appears that the EXPORTED_FUNCTIONS directive is being disregarded. The only plausible explanation is that the 'main' function is automatically exported, causing the confusion.

Answer №1

Kudos to Charles Ofria for helping me narrow down the issue. The only strange thing I encountered was related to the Emscripten Visual Studio plugin. I suspected it was automatically exporting the main function, which turned out to be correct. However, the reason the other function wasn't exporting was because I mistakenly placed it in the Additional Options section for Clang/C++ instead of the Emcc Linker.

The confusing part came when the Emcc Linker section didn't show up when I selected Console Application (.js) as the Configuration Type. To solve this, I changed the Target Extension to .html and the Configuration Type to Browser Application (.html). This made the Linker section appear again, allowing me to place the EXPORTED_FUNCTIONS option in the right place.

After rebuilding and transferring the output, both functions were defined and returned the correct values in the Javascript console.

Answer №2

It seems like the issue at hand is related to C++ name mangling. Since it is a C++ file, the name "gsr" gets transformed into something like "_Z3gsr". To prevent this, you can either convert it into a C file or wrap the method with extern "C".

For more information, check out

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending dynamic data through AJAX to a CodeIgniter controller is a common task that allows for seamless

Can anyone help me with retrieving data from a looping form in CodeIgniter? The form works fine, but I'm struggling to fetch the looping data in the controller. Here's my view (form): <form action="#" id="ap_data"> <div class="table-r ...

Warning C4308: integral constant with a negative value was converted to an unsigned type in boost serialization

Here is the structure I am using: struct member{ std::string ip_address; std::string port; protected: friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, ...

Event Listener for Spelling Quiz Buttons: Check Correct and Incorrect Answers

I am currently in the process of developing a spelling quiz for a project website using HTML, CSS, and JavaScript. The idea is to present the user with a word that has two missing letters indicated by underscores. The user then selects the correct answer ...

What is the best way to assign a unique background color to each individual card in my card list?

I have a list of cards and I want to assign a unique color to each card in the list. I attempted to do this on my own, but it ended up being more complex than I anticipated. Here is the list of cards: return ( <Container> <Row className=&qu ...

Guide to automatically update mysql posts every second

Utilizing ajax, I am able to save user posts/comments into a mysql table without the need for a page refresh. Initially, there is this <div id="posts-container"></div> Next, I attempted to use Jquery load() to iterate through a table and disp ...

What steps can I take to ensure my CSS component remains unaffected by the global CSS styles?

My navbar component is not displaying the styles correctly as intended. I have a Navbar.module.css file to style it, but after using next-auth for social login, only the buttons remain unstyled while everything else gets styled. The code snippet for impor ...

Challenges faced with react-bootstrap-autosuggest

After spending the entire day attempting to integrate the package from here into my create-react-app project upon ejection, I encountered the following error: Failed to compile. Error in ./~/react-bootstrap-autosuggest/lib/Autosuggest.js Module not found ...

Creating a consistent menu header across multiple webpages without the need to manually inserting the HTML on each individual page

Is there a way to display a consistent header across all web pages without manually duplicating the HTML code for each one? I'm looking to achieve this with JavaScript, without utilizing PHP. Would it be possible to leverage Angular JS ng-include func ...

Adding items to a dropdown list using AngularJS

I'm attempting to add an item to my dropdown list by targeting its ng-class after a save function in AngularJS. However, I am struggling to understand what the issue might be as I am still new to AngularJS. Any advice would be greatly appreciated: Dr ...

Having trouble preventing the scroll from moving even after setting body overflow to hidden in Next Js

I'm encountering an issue with my Nextjs project where I can't seem to prevent the page from scrolling even after using document.body.style.overflow set to hidden. Here is the code snippet: Code Sandbox Link Upon examining the code: In lines 11 ...

Switching to a jQuery IF statement instead of a FOR loop allows for more streamlined

I recently made a request to sqlite and am fetching data using the code snippet below: var rows = results.rows; alert(rows.length); for (var index = 0; index < rows.length; index++) { var x = rows.item(index); $( ...

Is there a way to retrieve random data based on either product id or slug within a single component using useQuery? Currently, all components are displaying the same data

Here is the code I wrote: const fetchCartItem = async () => { if (token) {const {data } = await axios.get(API.GET_PRODUCT_DETAILS_BY_PRODUCT_ID.replace("[ProductID]",item?.ProductID),{headers:{Authorization: token,},});setCartLoading(fal ...

Webpack fails to resolve paths provided by a JavaScript variable

I am currently developing an application using vue and ionic, but I have encountered an issue with loading assets as the paths are not resolving correctly. <template> <div id="index"> <img :src="image.src" v-for="image in image ...

CSS - owl carousel automatically stretches images to full width

Here is the code snippet that I am working with: $(document).ready(function() { $('.owl-carousel').owlCarousel({ loop:true, items:4, autoplay:true, autoplayTimeout:2000, autoplayHoverPause:true }); }); #owl-demo ...

Discovering the window.scrollTop, ScrollY, or any other distance value while utilizing CSS scroll snap can be achieved by following these

I am currently utilizing css scroll snap for smooth scrolling through sections that are 100vh in height. The functionality of the scroll snap is quite impressive. However, I need to find a way to determine the exact distance the user has scrolled down the ...

Graph your data with a stunning Fusioncharts area range graph combined with a sleek

My goal is to create a visual representation of an area range graph with a corresponding mid line. You can view the image below for reference: https://i.sstatic.net/8KDbF.png While I have successfully incorporated the low and high values, I am encounterin ...

Changing the designated materialUI class

Within the project, I am utilizing this theme: export const theme = createMuiTheme({ ...defaultThemeConfig, overrides: { ...defaultThemeConfig.overrides, MuiListItem: { root: { '&:nth-child(odd)': { backgro ...

Frequency of interrupts in Arduino

Utilizing an Arduino uno for speed measurement of a dc motor is my current project. I have successfully integrated an opto sensor that generates a pulse each time the motor completes a full rotation. However, I am encountering an issue when the motor speed ...

Utilizing two imports within the map() method

I have been considering the idea of incorporating two imports within map() in my React code. This is how my code looks: {this.state.dataExample.map(item => ( <ItemsSection nameSection={item.name} /> item.dat ...

jQuery plugin that controls scrolling speed using the mousewheel

I am trying to replicate the header design of Google+ which includes a search bar that moves when scrolling. Specifically, when the user scrolls down, the search bar shifts to top:-60px and the second horizontal menu shifts from top:60px to top:0 becoming ...