0

I use emcc to complie a C++ code into js. But how to pass args to C++ code?

#include<iostream>

int main(int argc, char** argv) {
  if (argc > 1)
    printf("%s", argv[1]);
}

build :

emcc ./test.cpp -sENVIRONMENT=shell -o test.js

pass commadline args into c code

TachyonicBytes
  • 700
  • 1
  • 8
Enzo
  • 1

1 Answers1

2

It seems that this stackexchange answer is similar to your use-case:

Place

Module['arguments'].push('first_param');
Module['arguments'].push('second_param');

before you run your function.

int main(int argc, char *argv[])
{
    assert(argc == 3);
    assert(strcmp(argv[1], "first_param") == 0);
    assert(strcmp(argv[2], "second_param") == 0);
}

Documentation reference

Edit:

So, I finally had time to install d8, and I made it work.

For me, in the generated test.js, there is this line:

if (Module['arguments']) arguments_ = Module['arguments'];legacyModuleProp('arguments', 'arguments_');

You have to place the arguments before this, so it should look like:

Module['arguments'] = [];
Module['arguments'].push('first_param');
Module['arguments'].push('second_param');

if (Module['arguments']) arguments_ = Module['arguments'];legacyModuleProp('arguments', 'arguments_');

You then compile with emcc and run with d8. I got another error because I did not end my printf call without a newline, so the output was not printing, a thing that seems to also happen in your code. Fortunately, there was an error message about the stdout not fully flushing, so I got to understand that was the problem.

TachyonicBytes
  • 700
  • 1
  • 8